如何将此原始查询转换为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
答案 0 :(得分:3)
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();
答案 1 :(得分:3)
我将修改 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
强>