如何查询all、orderby和paginate?

How can I query all, orderby, and paginate?

我不知道我的查询有什么问题,但计数显然是错误的,当我的总记录为12363

时它一直显示为1912

我试过了

在我的默认情况下更改此行

$q = Visitor::where('created_at', '<', now());

$q = Visitor::all(); but I got error; 

Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.


switch ($interval) {
    case 'day':
    $q = Visitor::where('created_at', '>', now()->today());
    break;
    case 'week':
    $q = Visitor::where('created_at', '>', now()->subWeek());
    break;
    case 'month':
    $q = Visitor::where('created_at', '>', now()->subMonth());
    break;
    case 'year':
    $q = Visitor::where('created_at', '>', now()->subYear());
    break;
    case 'last':
    $q = Visitor::where('created_at', '>', $last);
    break;
    default:
    $q = Visitor::where('created_at', '<', now());
    break;
}


$visitors = $q->orderBy('created_at', 'desc')->paginate(15);

http://app.test/visitor?interval=year

我得到 1912 - 正确


http://app.test/visitor

我得到了 1912 - 不正确的❌,它应该查询 all 因为没有指定间隔。

如果我这样做:

dd(count(Visitor::all()));

我得到了 12363 所以这应该是正确的值。

如果你发现我遗漏了什么,请告诉我

也许你可以使用 ->whereDate('created_at', now()),如果你需要 ->whereTime('created_at', '00:00:00')

$q = Visitor::all();returns一个Illuminate\Database\Eloquent\Collection.

调用 $visitors = $q->orderBy('created_at', 'desc')->paginate(15); 将在 Eloquent 集合上调用 ->orderBy(...),该方法在 class 中不存在。

解决方案

而不是:

$q = Visitor::where('created_at', '<', now()); ❌

使用这个:

$q = Visitor::query(); ✅