将原始查询转换为Laravel eloquent

时间:2016-05-18 08:20:02

标签: 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

2 个答案:

答案 0 :(得分:3)

First link

Second link

Query Builder

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();

Eloquent

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

相关问题