Laravel 5.多对多关系。构建查询

时间:2015-12-02 08:54:04

标签: php laravel-5 eloquent many-to-many

表:

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为字符串,给定对象

请帮帮我。

1 个答案:

答案 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();