[英]Eager loading: How to get a few photos from table with polymorph relationship
I wont to get a list of users with avatar and 4 photos like as on screenshot: 我不会获得具有头像和4张照片的用户列表,如屏幕截图所示:
User model: 用户模型:
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();
}]);
}
Photo model: 照片模型:
public function photoable()
{
return $this->morphTo();
}
I tried: 我试过了:
$users = User::with('avatar')->lastPhotos()->get();
but result had only avatar and empty photos collection: 但结果只有头像且照片集为空:
All photos are exists on table. 所有照片都在桌上。
I resolved this issue with mysql function 'group_concat': 我用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');
}
But 'group_concat' doesn't have 'limit' https://bugs.mysql.com/bug.php?id=30098 . 但“GROUP_CONCAT”没有“限制” https://bugs.mysql.com/bug.php?id=30098 。
For my task I used this decision: 对于我的任务,我使用了以下决定:
@foreach(explode(',', $user->hashes) as $hash)
{{ $hash }}
@break($loop->iteration == 4)
@endforeach
But maybe somebody know more elegant resolve? 但是也许有人知道更优雅的决心?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.