2016-05-18 145 views

回答

2

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

感谢您的帮助!乌尔查询生成器的方法是跑步,但雄辩的语言显示 调用未定义的方法照亮\数据库\查询\生成器::城市() –

+0

@WahidNahiyan'city'和'address'是该国模型的关系,两者都必须申报。 –

+0

是妳的权利..在大型项目中,有时很难与其他模型许多开发正在沿着管理模式,有些是经验较少,有的有更多的..我想查询生成器的方法是非常简单的,易于理解在哪里雄辩有它自己的方法和模型的声明..你有什么意见? 再次感谢您的帮助! –

2

我将修改的答案从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

+0

感谢您的帮助,但它表明 调用未定义的方法照亮\数据库\ @WahidNahiyan你查询\生成器::城市() –

+0

创建模型中的关系 –