2016-05-18 76 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

創建模型中的關係 –