Laravel为简单的查询制作者使用分页

时间:2016-02-01 11:33:49

标签: php laravel

在模型中这个简单的scope我想通过用户选项创建查询,遗憾的是我在下面的代码中得到了->paginate()的错误,我无法解决这个问题

错误:

Call to undefined function App\paginate()

我的范围代码:

public function scopeDate($query, $start, $finish, $type, $day, $order_type)
{
    $sub_query = $query;
    if (intval($day) == 0) {
        $sub_query
            ->where('created_at', '>=', date("Y-m-d") . ' 00:00:00')
            ->where('created_at', '<=', date("Y-m-d") . ' 24:00:00');
    } else {
        $sub_query
            ->where('created_at', '>=', date("Y-m-d", strtotime($start)) . ' 00:00:00')
            ->where('created_at', '<=', date("Y-m-d", strtotime($finish)) . ' 24:00:00');
    }

    if ($type != 0) {
        $sub_query->whereType($type);
    }

    $order_type == 0 ? $sub_query->orderBy('id', 'DESC'):$sub_query->orderBy('id', 'ASC') ;

    return $sub_query->paginate(50);
} 

1 个答案:

答案 0 :(得分:0)

这很好,但是如果你想分页结果怎么办?不幸的是,你不能只将Laravel的paginate方法链接到自定义静态方法。你应该使用

public function scopeDate($query, $start, $finish, $type, $day,$order_type)
{
$sub_query = $query;
if (intval($day) == 0) {
    $sub_query
        ->where('created_at', '>=', date("Y-m-d") . ' 00:00:00')
        ->where('created_at', '<=', date("Y-m-d") . ' 24:00:00');
} else {
    $sub_query
        ->where('created_at', '>=', date("Y-m-d", strtotime($start)) . ' 00:00:00')
        ->where('created_at', '<=', date("Y-m-d", strtotime($finish)) . ' 24:00:00');
}

if ($type != 0) {
    $sub_query->whereType($type);
}

$order_type == 0 ? $sub_query->orderBy('id', 'DESC'):$sub_query->orderBy('id', 'ASC') ;

return $sub_query;
} 

然后

Class::date($start, $finish, $type, $day, $order_type)->paginate(50);