Laravel方法Illuminate \ Database \ Eloquent \ Collection :: toSql不存在。错误

时间:2019-05-14 08:26:50

标签: php laravel-5 eloquent

我想从数据库中搜索所有记录,然后过滤这些记录,但是当我想使用

查看查询时
dd($posts->toSql());

它给了我错误

"Illuminate\Database\Eloquent\Collection::toSql does not exist."

它给了我一个错误

"Method Illuminate\Database\Eloquent\Collection::paginate does not exist."
$posts = Post::all();

        if( !is_null($brand) )
            $posts = $posts->where('brand', $brand);

        if( !is_null($car_type) )
            $posts = $posts->where('car_type', $car_type);

        if( !is_null($color) ){
            $posts = $posts->where('exterior_color', $color);
        }
        $posts = $posts->whereBetween('year',[$from_year,$to_year]);   
        $posts = $posts->whereBetween('milage',[$min_milage,$max_milage]);
        $posts = $posts->whereBetween('price',[$min_price,$max_price]);

        $posts = $posts->paginate(4);

        dd($posts->toSql());

2 个答案:

答案 0 :(得分:2)

首先,将Post::all()替换为Post::query()。在开始过滤之前,您正在获取所有结果。

paginate()方法将执行查询并将结果加载到Collection中,这意味着您正在集合上而不是查询构建器实例上调用toSql()

因此,您应该在致电toSql()之前先致电paginate(),或者如果要查看分页约束,则可以在服务提供商中运行查询/之前执行以下操作。

use Illuminate\Support\Facades\DB;

// ...

DB::listen(function ($query) {
    var_dump($query->sql);
});

答案 1 :(得分:2)

Laravel:5

->paginate()之后不能->toSql()Post::all() / Post::get()

您需要做什么:

在下面使用:

$posts = Post::query();

if( !is_null($brand) )
    $posts = $posts->where('brand', $brand);

$posts = $posts->whereBetween('year',[$from_year,$to_year]);   
$posts = $posts->whereBetween('milage',[$min_milage,$max_milage]);
$posts = $posts->whereBetween('price',[$min_price,$max_price]);

// $posts = $posts->paginate(4);

dd($posts->toSql());