Is there the best way/the simplest way to get all data where pivot?
I tried this $article = Article::with('category')->wherePivot('category_id', $category)->get();
but i got error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pivot' in 'where clause' (SQL: select * from `articles` where `pivot` = category_id)
The relation is many to many
Article
- id
- content
public function category(){ return $this->belongsToMany(Category::class, 'articles_has_categories', 'article_id', 'category_id'); }
Articles_Has_Categories
- id
- article_id
- category_id
public function article () { return $this->belongsTo(Article::class,'article_id'); } public function category () { return $this->belongsTo(Category::class,'category_id'); }
Category
- id
- name
public function article(){ return $this->belongsToMany(Article::class, 'articles_has_categories', 'category_id', 'article_id'); }
Advertisement
Answer
Please try this:
$article = Article::with(['category' => function($query) use ($category) { $query->where('category_id', $category); } ])->get();