2015-12-02 94 views
0

表:Laravel 5.多對多的關係。建立查詢

categories 
--id 

materials 
--id 

category_material 
--id 
--category_id 
--material_id 

型號:

class Material extends Model { 
    public function categories(){ 
     return $this->belongsToMany('App\Category'); 
    } 
} 

class Category extends Model { 
    public function materials(){ 
     return $this->belongsToMany('App\Material'); 
    } 
} 

我需要從 「CATEGORY_ID = 1」

所有材料嘗試:

$category_id = '1'; 
$materials = Material::with('categories')->where('category_id', $category_id)->get(); 

未知列「材料.category_id'

$category_id = '1'; 
$materials = Material::with(['categories',function($query) use ($category_id){ 
    $query->where('category_id', $category_id); 
}])->get(); 

ErrorException在Builder.php行792: 爆炸()預計參數2爲字符串,對象給出

請幫助我。

回答

0

陣列傳遞給with應該在relation_name => closure格式

$category_id = '1'; 
$materials = Material::whereHas('categories', function($query) use ($category_id){ 
    $query->where('category_id', $category_id); 
})->get(); 
+0

謝謝你,但現在:SQLSTATE [23000]:完整性約束違規:1052列「CATEGORY_ID」在where子句是曖昧 –

+0

添加數據透視表名到哪裏查詢和嘗試。假設它是'category_material',在where查詢'category_material.category_id'中使用它就像這樣。 – chanafdo

+0

不是erorrs,但我得到的所有材料(我只需要從「category_id = 1」) –