2015-12-02 113 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”) –