Laravel使用skip和take limit查询

时间:2015-06-12 14:09:15

标签: php sql laravel sql-limit

我尝试构建一个使用skip()和take()函数的查询,由于某种原因,它一直在最后添加offset 0,而不应该是LIMIT 0,0

代码:

    $dbSearch = new SchoolInfo;
    $dbSearch = $dbSearch->where(function($query) use($search) {

        $query->where('school_name', 'LIKE', '%'.$search.'%')
            ->orWhere('address_1', 'LIKE', '%'.$search.'%')
            ->orWhere('address_2', 'LIKE', '%'.$search.'%')
            ->orWhere('address_3', 'LIKE', '%'.$search.'%')
            ->orWhere('address_4', 'LIKE', '%'.$search.'%')
            ->orWhere('county', 'LIKE', '%'.$search.'%')
            ->orWhere('postcode', 'LIKE', '%'.$search.'%')
            ->orWhere('head_teacher_email', 'LIKE', '%'.$search.'%')
            ->orWhere('head_teacher_first', 'LIKE', '%'.$search.'%')
            ->orWhere('head_teacher_last', 'LIKE', '%'.$search.'%');
    });
    $results = $dbSearch
        ->skip($startat)
        ->take($startat)
        ->orderBy('school_name', 'ASC')
        ->get();

这是我得到的错误

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'offset 0' at line 1 (SQL: select * from `school_info` where (`school_name` LIKE %ok% or `address_1` LIKE %ok% or `address_2` LIKE %ok% or `address_3` LIKE %ok% or `address_4` LIKE %ok% or `county` LIKE %ok% or `postcode` LIKE %ok% or `head_teacher_email` LIKE %ok% or `head_teacher_first` LIKE %ok% or `head_teacher_last` LIKE %ok%) order by `school_name` asc offset 0)","file":"\/var\/www\/html\/globalrecruit\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Connection.php

1 个答案:

答案 0 :(得分:2)

当您执行skip(n)时,它会向您的查询添加offset n,正如您所注意到的那样。当您执行take(n)时,它会为查询添加n的限制。然后,在构造实际查询时,该限制将覆盖偏移量。

但是take(0),你说你想要零结果。 Eloquent认为你不想申请限制,所以不这样做。相反,只剩下偏移量,并且本身不构成有效查询。

确保take()值大于零,你应该没问题。 :)

(注意:对于工会化查询,这不完全正确,但这完全不同。)