Search code examples
phplaravel-5eloquentmany-to-many

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


Tables:

categories
--id

materials
--id

category_material
--id
--category_id
--material_id

Models:

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

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

I need all materials from "category_id = 1"

Trying:

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

Unknown column 'materials.category_id'

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

ErrorException in Builder.php line 792: explode() expects parameter 2 to be string, object given

Help me, please.


Solution

  • Array passed to with should be in relation_name => closure format

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