获取 pivot id (Laravel) 所在的所有数据
Get all data where pivot id (Laravel)
是否有最好的 way/the 最简单的方法来获取所有数据的枢轴?
我尝试了这个 $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)
关系是多对多
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');
}
$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);
请试试这个:
$article = Article::with(['category' => function($query) use ($category) {
$query->where('category_id', $category);
}
])->get();
是否有最好的 way/the 最简单的方法来获取所有数据的枢轴?
我尝试了这个 $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)
关系是多对多
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');
}
$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);
请试试这个:
$article = Article::with(['category' => function($query) use ($category) {
$query->where('category_id', $category);
}
])->get();