0

My Eloquent models are described below:

class Product extends Eloquent{

...
    public function categories(){
        return $this->belongsToMany('Category');
    }
...
}

class Category extends Eloquent{

...
    public function products(){
        return $this->belongsToMany('Product');
    }
...
}

How do I write a cleanly structured query for whether a given product is in a category?

Extra love if it can be a method of the class!

My closest (and very messy) attempt is something like:

$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
mike
  • 1,786
  • 2
  • 19
  • 31
  • I used deczo's second suggestion to solve my dilemma. See my Gist at https://gist.github.com/mikeritter/efa50a3d123d836eb862 – mike Jul 21 '14 at 06:51

1 Answers1

1

The easiest way to check, whether the relation exists, would be:

$product = Product::whereHas('categories', function ($q) use ($categoryId) {
    $q->where('categories.id', $categoryId);
})->findOrFail($productId);

This will return the product instance or throw ModelNotFoundException if it was not found (meaning no product for given id or the product has no relation with the given category).

// or:
$product = Product::find($id);

$product->categories()->where('categories.id', $categoryId)->exists(); // true/false

You can also check this one for more clues: MySQL nested resources (pivot tables) permission to view/update/manage


Also you can use contains on the collection:

$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
Community
  • 1
  • 1
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157