[英]Get all data where pivot id (Laravel)
有沒有最好的方法/最簡單的方法來獲取 pivot 的所有數據? 我試過這個$article = Article::with('category')->wherePivot('category_id', $category)->get();
但我有錯誤
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pivot' in 'where clause' (SQL: select * from `articles` where `pivot` = category_id)
關系是多對多的
文章
- ID
- 內容
public function category(){
return $this->belongsToMany(Category::class, 'articles_has_categories', 'article_id', 'category_id');
}
文章_有_分類
- ID
- article_id
- 類別ID
public function article ()
{
return $this->belongsTo(Article::class,'article_id');
}
public function category ()
{
return $this->belongsTo(Category::class,'category_id');
}
類別
- ID
- 姓名
public function article(){
return $this->belongsToMany(Article::class, 'articles_has_categories', 'category_id', 'article_id');
}
請試試這個:
$article = Article::with(['category' => function($query) use ($category) {
$query->where('category_id', $category);
}
])->get();
$article = Article::with(['category' => function($query) use ($category) {
$query->whereHas('category_id', $category);
}
])->get();
如果您使用$category
作為數組,則使用$query->whereHas('category_id', $category);
否則,如果您使用$category
是單個 id $query->where('category_id', $category);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.