2017-06-21 33 views
0

我不會得到與化身用戶和4張名單像上截圖:enter image description here預先加載:如何從表中的幾張照片與多晶型關係

用戶模式:

public function avatar() 
    { 
     return $this->morphOne(Photo::class, 'photoable') 
     ->where('photoable_type', 'user'); 
    } 

    public function photos() 
    { 
    return $this->morphMany(Photo::class, 'photoable') 
     ->where('photoable_type', 'photo'); 
    } 

    public function scopeLastPhotos($query) 
    { 
     return $query->with(['photos' => function ($query) { 

     $query->take(4)->get(); 

     }]); 
    } 

照片模式:

public function photoable() 
    { 
     return $this->morphTo(); 
    } 

我想:

$users = User::with('avatar')->lastPhotos()->get(); 

,但結果只有頭像和空照片集:

enter image description here

所有照片都是存在於表。

回答

0

我解決了這個問題與MySQL功能 'GROUP_CONCAT':

public function scopeLastPhotos($query) 
{ 
    return $query->join('photos', 'photos.photoable_id', 'users.id') 
     ->selectRaw('users.*, group_concat(photos.hash) as hashes') 
     ->where('photos.photoable_type', 'photo') 
     ->groupBy('photos.photoable_id'); 
} 

但 'GROUP_CONCAT' 沒有 '限制' https://bugs.mysql.com/bug.php?id=30098

對於我的任務我用這個決定:

@foreach(explode(',', $user->hashes) as $hash) 

    {{ $hash }} 

    @break($loop->iteration == 4) 

@endforeach 

但也許有人知道更優雅的決心?