如何将参数绑定到模型上使用的 Laravel 中的原始数据库查询?

2022-01-08 00:00:00 php mysql laravel pdo laravel-4

回复,

我有以下疑问:

$property = 
    Property::select(
        DB::raw("title, lat, lng, ( 
            3959 * acos( 
                cos( radians(:lat) ) * 
                cos( radians( lat ) ) * 
                cos( radians( lng ) - radians(:lng) ) + 
                sin( radians(:lat) ) * 
                sin( radians( lat ) ) 
            ) 
        ) AS distance", ["lat" => $lat, "lng" => $lng, "lat" => $lat])
    )
    ->having("distance", "<", $radius)
    ->orderBy("distance")
    ->take(20)
    ->get();

不起作用:无效参数号:混合命名参数和位置参数.

有谁知道技巧或解决方法(我显然可以编写完整的查询,但更喜欢使用流利的构建器).

Does anyone know a trick or a workaround (I can obviously write the full query but prefer to use fluent builder).

推荐答案

好的,经过一些实验,这是我想出的解决方案:

OK, after some experimenting, here's the solution that I came up with:

$property = 
    Property::select(
        DB::raw("title, lat, lng, ( 
            3959 * acos( 
                cos( radians(  ?  ) ) *
                cos( radians( lat ) ) * 
                cos( radians( lng ) - radians(?) ) + 
                sin( radians(  ?  ) ) *
                sin( radians( lat ) ) 
            )
       ) AS distance")
    )
    ->having("distance", "<", "?")
    ->orderBy("distance")
    ->take(20)
    ->setBindings([$lat, $lng, $lat,  $radius])
    ->get();

基本上,setBindings 必须在查询中调用.希望这被记录在案!

Basically, setBindings has to be called on the query. Wish this was documented!

相关文章