表:
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();
未知栏' materials.category_id'
$category_id = '1';
$materials = Material::with(['categories',function($query) use ($category_id){
$query->where('category_id', $category_id);
}])->get();
Builder.php第792行中的ErrorException: explode()期望参数2为字符串,给定对象
请帮帮我。
答案 0 :(得分:0)
传递给with
的数组应为relation_name => closure
格式
$category_id = '1';
$materials = Material::whereHas('categories', function($query) use ($category_id){
$query->where('category_id', $category_id);
})->get();