使用Eloquent的复杂计算值

时间:2014-06-28 14:51:46

标签: laravel laravel-4 eloquent

我有两张桌子,商店和地点。

现在我正在这样做:

$shops = Shop::with('location');
if (Input::has('location')) {
    $shops->whereHas('location', function($q) use ($input) {
        $q->where('name', '=', Input::get('location');
    });
}

return $shops->paginate(10);

这一切都很顺利。

但是,我还要包括一个距离值,并按它排序。这基本上相当于创建一个计算值,我尝试这样做:

$shops->raw('(
    3959 * acos (
        cos ( radians(?) )
   * cos( radians( locations.lat ) )
   * cos( radians( locations.lon ) - radians(?) )
        + sin ( radians(?) )
   * sin( radians( locations.lat ) )
        )
) AS distance
', array(Session::get('latitude'), Session::get('longitude'), Session::get('latitude')));

(放在上面的返回值之前)

这没有做任何事情 - 交换到whereRaw也不起作用。

我是否必须停止使用Eloquent(再次!),或者这是Eloquent可以处理的事情?

2 个答案:

答案 0 :(得分:2)

  1. 您需要selectRawselect(DB::raw(...)),而不是whereRaw
  2. 您需要加入locations表格才能从中选择(在Shop个对象上附加距离)将该部分放入查询加载{{1模型(将距离附加到Location个对象):

    Location
  3. 如果您想按距离订购商店,那么您肯定需要加入。

答案 1 :(得分:-1)

在对IRC提供一些帮助之后,这就是我决定这样做的方式:

// First, specify a manual join onto locations, so the values are available in this query
$shops->join('locations', 'shops.location_id', '=', 'locations.id');

// Second, add the selectRaw (which seems to not have variable binding?)
$shops->selectRaw('(
    3959 * acos (
        cos ( radians('.Session::get('latitude').') )
* cos( radians( locations.lat ) )
* cos( radians( locations.lon ) - radians('.Session::get('longitude').') )
        + sin ( radians('.Session::get('latitude').') )
* sin( radians( locations.lat ) )
        )
) AS distance
');

// select the rest of the variables on shops afterwards to avoid any name collisons
$shops->addSelect('shops.*');