【发布时间】:2021-08-06 03:38:42
【问题描述】:
我有 3 张桌子 products、prices、cats。
我需要按cats 过滤product 并按price 排序,但我有一个问题:
这段代码运行良好,但需要分页。
$products = Product::with('photo', 'price', 'brand')
->whereHas('cats', function ($q) use ($cat) {
$q->where('cat_id', $cat->id);
})
->get()
->sortByDesc(function($query) {
return $query->price->price;
});
一开始我是这样做的:
$products = Product::with('photo', 'price', 'brand')
->whereHas('cats', function ($q) use ($cat) {
$q->where('cat_id', $cat->id);
})
->paginate($page)
->sortByDesc(function ($query) {
return $query->price->price;
});
但是links() 不起作用。
在我这样做之后:
$products = Product::with('photo', 'price', 'brand')
->whereHas('cats', function ($q) use ($cat){
$q->where('cat_id', $cat->id);
})
->paginate($page);
$products->setCollection(
$products->sortBy(function ($query) {
return $query->price->id;
})
);
但是sortBy 不起作用。
所以我不能通过连接价格表使用orderBy()
因为当我这样做时,我可以显示所有产品,而我无法按类别过滤产品
我的脑子不行了,如果有人能帮助我,我将非常感激
【问题讨论】:
-
确保在
paginate()之前使用orderBy() -
您可以将 orderBy 用作
orderBy('prices.id', 'DESC')Product::with('photo','price','brand')->whereHas('cats', function($q) use($cat){ $q->where('cat_id',$cat->id);})->orderBy('prices.id', 'ASC')->paginate($page);之类的东西 -
在我测试它之前 orderBy('prices.id', 'DESC') 但我有错误 Illuminate\Database\QueryException SQLSTATE[42S22]: Column not found: 1054 Unknown column 'prices.id'在'顺序子句'(SQL:select * from
productswhere exists(select * fromcatsinner joincat_productoncats.id=cat_product.cat_idwhereproducts.@ 987654345@ =cat_product.product_id和cat_id= 3) order byprices.idasc limit 1 offset 0)
标签: laravel laravel-5 eloquent laravel-4