【问题标题】:i need pagination with sortBy in laravel我需要在 laravel 中使用 sortBy 进行分页
【发布时间】:2021-08-06 03:38:42
【问题描述】:

我有 3 张桌子 productspricescats

我需要按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 products where exists(select * from cats inner join cat_product on cats.id = cat_product.cat_id where products.@ 987654345@ = cat_product.product_idcat_id = 3) order by prices.id asc limit 1 offset 0)

标签: laravel laravel-5 eloquent laravel-4


【解决方案1】:

相信你也可以做到:

Product::join('price', 'price.id', '=', 'photo.price_id')
                ->orderBy('price.price', 'asc')
                ->select('photo.*')
                ->paginate(10);

【讨论】:

  • 它不起作用,我确实在我的问题中解释过,当然你的代码也有问题
猜你喜欢
  • 2017-05-03
  • 2019-03-12
  • 2014-01-30
  • 2021-12-13
  • 2021-10-07
  • 2019-11-04
  • 2014-09-01
  • 1970-01-01
  • 2020-03-07
相关资源
最近更新 更多