问题
I'm working on a Laravel project and trying to convert this query into an eloquent query so I can eager load other relationships.
$restaurants = DB::query('SELECT *, ( 3959 * acos( cos( radians(21.420639) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-157.805745) ) + sin( radians(21.420639) ) * sin( radians( lat ) ) ) ) AS distance FROM restaurants GROUP BY id HAVING distance < 25 AND ratingsTotal > 0 ORDER BY distance LIMIT 0 , 5');
Any help on how this should look would really be appreciated.
回答1:
Your model is going to look something like this in Laravel 4. L3 is probably fairly similar but I have little-to-no experience with that.
<?php
class Restaurant extends Illuminate\Database\Eloquent\Model
{
protected $table = 'restaurants';
public function getSomeShit()
{
return $this
->select('*')
->select(DB::raw('( 3959 * acos( cos( radians(21.420639) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-157.805745) ) + sin( radians(21.420639) ) * sin( radians( lat ) ) ) ) AS distance'))
->groupBy('id')
->having('distance', '<', 25)
->having('ratingsTotal', '>', 0)
->orderBy('distance')
->limit(5);
}
}
Remember, that you never put complicated (or any) database logic in the controller, always behind a view.
回答2:
Might want to cache those radius calculations. Each one can take up 300 to 500ms per calculation. More with order_by clause. I ran this offline and pushed it to a redis cache with zip-distanc-units as the key.
来源:https://stackoverflow.com/questions/14508549/convert-this-query-for-eloquent