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

Laravel 5. Many-to-many relationsip. Build query

表:

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

第 792 行 Builder.php 中的错误异常: explode() 期望参数 2 为字符串,给定的对象

请帮帮我。

传递给 with 的数组应采用 relation_name => closure 格式

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