我的雄辩模型如下所述:
class Product extends Eloquent{
...
public function categories(){
return $this->belongsToMany('Category');
}
...
}
class Category extends Eloquent{
...
public function products(){
return $this->belongsToMany('Product');
}
...
}
如何针对特定产品是否属于某个类别编写结构清晰的查询?
额外的爱,如果它可以成为班级的方法!
我最接近(而且非常混乱)的尝试类似于:
$categories = Category::all();
$product = Product::find($id);
$id = 3;
foreach($categories as $cat)
while($cat->products())
if($product->id === $cat->products()->id)
true
endif
endwhile
endforeach
答案 0 :(得分:1)
检查关系是否存在的最简单方法是:
$product = Product::whereHas('categories', function ($q) use ($categoryId) {
$q->where('categories.id', $categoryId);
})->findOrFail($productId);
如果找不到产品实例,则会返回产品实例或抛出ModelNotFoundException
(意味着没有给定ID的产品或产品与给定类别无关)。
// or:
$product = Product::find($id);
$product->categories()->where('categories.id', $categoryId)->exists(); // true/false
您还可以查看此内容以获取更多线索:MySQL nested resources (pivot tables) permission to view/update/manage
此外,您可以在集合中使用contains
:
$categories = Category::with('products)->get();
$product = Product::find($id);
foreach ($categories as $category)
{
if ($category->products->contains($product)
{
// do something
}
}
// note:
$category->products; // Eloquent Collection object
$category->products(); // BelongsToMany relation object