将变量绑定到原始查询

时间:2015-06-01 14:34:33

标签: laravel laravel-4 eloquent laravel-5

我正在尝试将变量绑定到我的原始查询:

$data = $myModel->select( DB::raw('(3959 * acos(cos(radians(:lat)) * cos(radians(lat)) * cos(radians(lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(lat)))) as distance'), array(
        'lat' => $lat, 'lng' => $lng,
    ))->orderBy('distance', 'ASC')->having('distance', '<', $radius)
    ->get();

我已经查看了导致这篇博文的各种SO帖子:

http://fideloper.com/laravel-raw-queries

我仍然收到错误:

strtolower() expects parameter 1 to be string, array given

我哪里错了?

1 个答案:

答案 0 :(得分:2)

您必须将变量绑定到raw方法而不是select

$select = "(3959 * acos(cos(radians(:lat)) * cos(radians(lat)) * cos(radians(lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(lat)))) as distance";
$data = $myModel->select( DB::raw($select,array(
    'lat' => $lat, 'lng' => $lng,
)))->orderBy('distance', 'ASC')->having('distance', '<', $radius)
->get();

或直接使用selectRaw方法:

$data = $myModel->selectRaw($select,array(
    'lat' => $lat, 'lng' => $lng,
))->orderBy('distance', 'ASC')->having('distance', '<', $radius)
->get();