Php 在使用雄辩的orm时,如何让只有第一个孩子的父母?
我正在尝试从我的相册表中获取activei.e active=1个相册,其中至少有1个活动图像,第一个活动图像按创建日期的降序排列。i、 e每个相册的图像必须是要创建的最后一个活动图像 我的相册型号是:Php 在使用雄辩的orm时,如何让只有第一个孩子的父母?,php,laravel,eloquent,parent-child,Php,Laravel,Eloquent,Parent Child,我正在尝试从我的相册表中获取activei.e active=1个相册,其中至少有1个活动图像,第一个活动图像按创建日期的降序排列。i、 e每个相册的图像必须是要创建的最后一个活动图像 我的相册型号是: class Album extends Model { public function images() { return $this->hasMany('Images','album_id'); } public function sco
class Album extends Model {
public function images()
{
return $this->hasMany('Images','album_id');
}
public function scopeActive($query){
return $query->where('is_active', 1);
}
}
我的图像模型是:
class Images extends Model {
public function scopeActive($query){
return $query->where('is_active', 1);
}
public function album(){
return $this->belongsTo('Album', 'album_id', 'id');
}
}
到目前为止,我已经得出以下结论:
$albums = Album::with(['images' => function($query){
$query->orderBy('created_at', 'desc');
$query->first();
}])
->whereHas('images', function ($query) {
$query->active();
})
->active()
->get();
上述结果将为我提供以下阵列,其中仅包含一个相册的图像:
Array
(
[0] => Array
(
[id] => 2
[name] => Test Gallery
[slug] => test-gallery
[description] => this is test gallery
[cover_image] =>
[is_active] => 1
[created_by] => 2
[updated_by] => 2
[deleted_at] =>
[images] => Array
(
)
)
[1] => Array
(
[id] => 3
[name] => My Gallery 2
[slug] => my-gallery-2
[description] => Hello, this is my second gallery.
[cover_image] =>
[is_active] => 1
[created_by] => 2
[updated_by] =>
[deleted_at] =>
[images] => Array
(
[0] => Array
(
[id] => 9
[album_id] => 3
[image] => gallery_xfWjm0JuzZ.jpg
[description] =>
[is_active] => 1
[created_by] => 2
[updated_by] =>
[deleted_at] =>
)
)
)
)
谁能帮我实现我的目标 您应该尝试以下方法:
class Album extends Model
{
public function image()
{
return $this->images()
->active()
->orderBy('created_at', 'desc')
->take(1)
->first();
}
public function images()
{
return $this->hasMany('Images','album_id');
}
public function scopeActive($query){
return $query->where('is_active', 1);
}
}
$albums = Album::active()->whereHas('images', function ($query) {
$query->active();
})->get();
foreach ($albums as $album) {
var_dump($album->image());
}
您所需要的只是whereHas方法:
它将检索至少有一个活动图像的所有相册您当前的查询结果是什么?请再次查看问题,我已添加了从查询中获得的数组结果。但这不会检索所有相册的第一个图像,对吗?这会起作用,但会执行n+1查询。应该避免。是的,我注意到了。你知道在这种情况下如何避免吗?
$albums = Album::whereHas('images', function ($query) {
$query->where('is_active', 1)->orderBy('created_at', 'desc');
})->get();