laravel 4原始查询错误

时间:2014-02-10 22:23:51

标签: php mysql laravel-4

我目前正在尝试构建一个原始查询以检索“附近”,这是我的尝试

$places = DB::select('select * from b_details where(3959 * acos(cos(radians(37)) * cos(radians(lat = ?)) * cos(radians(lng = ?) - radians(-122)) + sin(radians(37)) * sin(radians(lat))))
as distance from b_details having distance < radius = ?  order by distance LIMIT 0 , 20', array($lat, $lng, $radius));

我也尝试过:

    $disctance_select = sprintf(
        "( 3959 * acos( cos( radians(%s) ) " .
        " * cos( radians( lat ) ) " .
        " * cos( radians( lng ) - radians(%s) ) " .
        " + sin( radians(%s) ) * sin( radians( lat ) ) " .
        ") " .
        ") " .
        "AS distance",
        $lat,
        $lng,
        $lat
    );

    return DB::table('b_details')
        ->having('distance', '<', $radius)
        ->orderBy('distance', 'ASC')
        ->get(array('*',$disctance_select));

这会产生错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax

这是我试图复制用于laravel 4的查询:

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

请检查一下: 它确实有效:)

$result = Listing::select(
            DB::raw("*,
                          ( 6371 * acos( cos( radians(?) ) *
                            cos( radians( lat ) )
                            * cos( radians( lon ) - radians(?)
                            ) + sin( radians(?) ) *
                            sin( radians( lat ) ) )
                          ) AS distance"))
            ->having("distance", "<", $radius)
            ->orderBy("distance")
            ->setBindings([$lat, $lon, $lat])
            ->get();

答案 1 :(得分:0)

您已完成select *,后跟where,后跟calculated column。您需要将distance计算列放在where子句之前。

为什么不能只将您要复制的查询粘贴为Laravel DB:select中的第一个参数?我很困惑你为什么要改变它。