【问题标题】:OFFSET and LIMIT not working in laravel Eloquent?OFFSET 和 LIMIT 在 laravel Eloquent 中不起作用?
【发布时间】:2021-03-24 08:20:44
【问题描述】:

我正在尝试对 Laravel eloquent 使用偏移和限制。

$start_from = 0;
$limit = 2;
$invoices = Invoice::where('calculation_complete',0)
    ->offset($start_from)
    ->limit($limit)
    ->get();

不是给我 2 条记录,而是给我所有记录。哪里出了问题,我在其他地方使用它,它工作正常。

【问题讨论】:

  • 为什么不使用paginate()方法?
  • 你的底层数据库是什么?您还可以分享生成的实际查询(使用例如dd(Invoice::where....->toSQL())
  • 那些方法有效,检查你的代码的其余部分,也许你正在用另一个调用 $invoices = $user->invoices 或类似的东西覆盖变量。在所有情况下,都没有足够的详细信息来帮助您。

标签: php laravel eloquent laravel-8


【解决方案1】:

Laravel 有自己的函数 skip 用于 offsettake 用于 limit

试试这个:

$start_from = 0;
$limit = 2;

$invoices = Invoice::where('calculation_complete',0)
                ->orderBy('id','DESC')
                ->skip($start_from)
                ->take($limit)
                ->get();

或者,您可以使用paginate

$invoices = Invoice::where('calculation_complete',0)
                ->orderBy('updated_at', 'desc')->paginate($limit);

【讨论】:

  • 这可能是答案,但请解释为什么您认为它会有所帮助。 From the docs你可以使用limit和offset方法。这些方法在功能上等同于 take 和 skip 方法,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
  • 2012-08-25
  • 2013-04-13
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
相关资源
最近更新 更多