首页 文章

将原始查询转换为Laravel eloquent

提问于
浏览
2

如何将此原始查询转换为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 回答

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

    我将修改 Andrey Lutscevich 雄辩部分的答案

    Country::select('country.name as country')->has('city')
      ->whereHas('address', function ($query)
      {
        $query->where('id', 1);
      })
      ->get();
    

    查询关系存在在访问模型的记录时,您可能希望根据在这种情况下使用的关系的存在来限制结果WhereHas方法将“where”条件放在您的查询上

相关问题