I have the following table structure:
products
- id
product_formats
- id
- product_id
product_prices
- id
- product_format_id
- market_id
markets
- id
A product can have multiple formats, with each having their own price which belongs in a different market. How can I retrieve the list of Markets from the Product model?
I used to have a single pivot table, however now I have two pivot.
class Product extends Model
{
public function markets()
{
return $this->belongsToMany(Market::class);
}
}
Update
To get the result I want, I did the following:
public function markets()
{
return Market::whereIn('id', $this->prices()->distinct()->pluck('market_id')->toArray());
}
However, I'm wondering if there's a way to accomplish this via a relationship.
one to many
relation betweenproducts
andproduct_formats
and amany to many
relation betweenproduct_formats
andmarkets
- Luis felipe De jesus Munoz$product->product_format[0]->markets
. I saidformat[0]
because of the one to many relation - Luis felipe De jesus Munozmarkets->whereHas("product_formats.products", function($query){$query->where("id", myProductId);})->get()
- Luis felipe De jesus Munoz