Reputation: 5
Im trying to solve this problem with relationships in the pivot table. i have 3 tables (products, collections, collection_product)
products table id name size_id
collections table id name
collection_product table id (I know... i must use attach and detach) but later i will figure it out how to solve it) collection_id product_id
MODELS
Product Model
public function collections()
{
return $this->belongsToMany(Collection::class);
}
Collection Model
public function products()
{
return $this->belongsToMany(Product::class, 'collection_product');
}
ProductCollection Pivot Table
class ProductCollection extends Pivot
{
protected $table = 'collection_product';
public function collections()
{
return $this->hasMany(Collection::class, 'collection_id');
}
public function products()
{
return $this->hasMany(Product::class, 'product_id');
}
}
and in my CollectionController i want to search one collection and for all the products shown in the collection i want to show in the blade view only the size "SMALL" (size_id) products but i dont know how to code it in my controller, because first i need to fix the relationships and then figure out how to declare a condition to take size_id of my products table.
Upvotes: 0
Views: 131
Reputation: 50561
You can eager load the products for the collection you want and constrain what it loads:
$col = Collection::with('products', fn ($q) => $q->where('size_id', ...))
->findOrFail(...);
@foreach ($col->products as $product)
...
@endforeach
You could also get all the products and filter them before iterating them:
$col = Collection::findOrFail(...);
@foreach ($col->products->where('size_id', ...) as $product)
...
@endforeach
Upvotes: 0