mercredi 2 décembre 2015

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.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1l71pnv
via IFTTT

Aucun commentaire:

Enregistrer un commentaire