我有一个查询来获取具有某些关系的产品,但是当添加"orderBy('updated_at', 'desc')
时,与产品图像的关系变成一个空数组。
我从:
开始$products = \App\Product::where('id', '>', 0)
->with('designer')
->whereIn('id', [$someIds]);
然后,我继续添加与“ whereHas”查询的某些关系(如果我将其删除,则问题仍然存在)
最后,如果我这样做:
return $products
->with('gallery.items')
->orderBy('updated_at', 'desc')->paginate($args['count']);
gallery.items
数组为空。如果我使用'asc'
而不是'desc'
,则效果很好。我也尝试过orderByDesc
方法,但这是同一回事。
如果更改顺序,在添加“ with”关系之前执行orderBy,它还会为图库图像返回空数组:
return $products->orderBy('updated_at', 'desc')
->with('gallery.items')
->paginate($args['count']);
修改: 我可以进行更简单的查询来缩小问题范围:
return $products = \App\Product::take(30)
->orderBy('updated_at', 'desc')
->with('gallery.items')
->get();
^^这也给出了空的图库项目。如果删除->orderBy('updated_at', 'desc')
,则图库项目将按应有的方式显示。同样,“ asc”有效(这是默认排序)。
更新:
这是上面的^^查询,以\DB::enableQueryLog()
记录:
{
"query": "select * from `products`
order by `updated_at` desc limit 30",
"bindings": [],
"time": 26.46
},
{
"query": "select * from `galleries` where `galleries`.`id`
in (?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
"bindings": [
3970,3971,3973,3974,3975,3976,3977,3978,3979,3980,3981,3982,3983,3984,
3985,3986,3987,3988,3989,3990,3991,3992,3993,3994,3995,3996,3997,3998,
3999,4000],
"time": 3.64
},
{
"query": "select `uploads`.*,
`gallery_items`.`gallery_id` as `pivot_gallery_id`,
`gallery_items`.`upload_id` as `pivot_upload_id`,
`gallery_items`.`order` as `pivot_order`
from `uploads`
inner join `gallery_items` on `uploads`.`id` = `gallery_items`.`upload_id`
where `gallery_items`.`gallery_id`
in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?)",
"bindings": [
3970,3971,3973,3974,3975,3976,3977,3978,3979,3980,3981,3982,
3983,3984,3985,3986,3987,3988,3989,3990,3991,3992,3993,3994,3995,
3996,3997,3998,3999,4000],
"time": 48.92
修改2: Gallery模型上的gallery.items关系是这样的:
items(){
return $this->belongsToMany('\App\Upload', 'gallery_items','gallery_id','upload_id')
->withPivot('order');
}