【发布时间】:2016-09-14 14:34:20
【问题描述】:
如何将此原始查询转换为 Laravel 雄辩的方式:
select c.name as country from country c, address ad, city ci where
ad.id = 1 and city.id = ad.city_id and c.code = ci.country_code
【问题讨论】:
标签: sql laravel eloquent inner-join
如何将此原始查询转换为 Laravel 雄辩的方式:
select c.name as country from country c, address ad, city ci where
ad.id = 1 and city.id = ad.city_id and c.code = ci.country_code
【问题讨论】:
标签: sql laravel eloquent inner-join
我会从Andrey Lutscevich雄辩的部分修改答案
Country::select('country.name as country')->has('city')
->whereHas('address', function ($query)
{
$query->where('id', 1);
})
->get();
查询关系存在 在访问模型的记录时,您可能希望根据关系的存在来限制结果,在这种情况下使用
has
WhereHas methods put "where" conditions on your has queries
【讨论】:
DB::table("country")
->join('city', 'city.country_code', '=', 'country.user_id')
->join('address', 'address.city_id', '=', 'city.id')
->select('country.name as country')
->where('address.id', 1)
->get();
Country::with(['city','address' => function($query){
return $query->where('id', 1)
}])
->select('country.name as country')
->get();
【讨论】:
city 和 address 是 Country 模型中的关系,两者都必须声明。