Convert raw query to Laravel eloquent

和自甴很熟 提交于 2019-12-31 02:55:25

问题


How to convert this raw query to Laravel eloquent way:

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

回答1:


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



回答2:


I will modify the answer from Andrey Lutscevich eloquent part

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

Querying Relationship Existence When accessing the records for a model, you may wish to limit your results based on the existence of a relationship use has in that case

WhereHas methods put "where" conditions on your has queries



来源:https://stackoverflow.com/questions/37293971/convert-raw-query-to-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!