我的Eloquent模型描述如下:
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
检查关系是否存在的最简单方法是:
$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嵌套资源(数据透视表)权限查看/更新/管理
也可以在集合上使用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