If your model has a relationship with 2 different model using the same foreign key, consider using Polymorphic relationship.
https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-polymorphic-relations
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello,
I have these 3 tables: order_items, beans, blends
order_items has a field called: product_id
product_id can be a bean or a blend.
Do I do the relationships like this?
orderItem Model:
public function bean()
{
return $this->belongsTo(Bean::class);
}
public function blend()
{
return $this->belongsTo(Blend::class);
}
And in Bean and Blend Models:
public function orderItems()
{
return $this->hasMany(OrderItem::class, 'product_id');
}
Thanks
@SigalZ First you need to change order_items table column to support polymorphic relationship. In your migration file, you need to update, product_id column to like this below
$table->morphs('productable', 'produtable_index');
It will generate two columns, producatable_type, productable_id.
productable_type column store model,productable_type column store model primary key.In your 'OrderItem` model, add relationship like this
public function productable()
{
return $this->morphTo();
}
In your Bean & Blend models, add relationship like this
public function OrderItems(): MorphMany
{
return $this->morphMany(OrderItem::class, 'produtable');
}
If order_id is primary key in you order_items table, then you can use it with eargar loading to fetch related tables data also.
OrderItem::with('produtable')->firstWhere('order_id', 1);
Hope this will help you.
Please or to participate in this conversation.