将此查询转换为 eloquent

2021-12-26 00:00:00 mysql laravel eloquent

我正在处理一个 Laravel 项目并尝试将此查询转换为雄辩的查询,以便我可以急切地加载其他关系.

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.

推荐答案

你的模型将在 Laravel 4 中看起来像这样.L3 可能非常相似,但我几乎没有经验.

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 IlluminateDatabaseEloquentModel
{
    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.

相关文章