Laravel 4 如何查询有说服力的多对多关系,以查看模型实例是否在集合中?

Laravel 4 如何查询有说服力的多对多关系,以查看模型实例是否在集合中?,laravel-4,eloquent,Laravel 4,Eloquent,我的雄辩模型描述如下: class Product extends Eloquent{ ... public function categories(){ return $this->belongsToMany('Category'); } ... } class Category extends Eloquent{ ... public function products(){ return $this->belongs

我的雄辩模型描述如下:

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没有产品,或者产品与给定类别没有关系)

您还可以查看此项以了解更多线索:


您还可以在收藏中使用
包含

$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

我用德佐的第二个建议来解决我的困境。见我的要点
$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