Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

m24mohammadi's avatar

laravel relationship between 3 tables

I have 3 tables (Models)

Advertise : id title ...

Value: id title amount ....

Field: id name title ...

and my pivot tables is like advertise_id value_id field_id

how can I set relations in my models and do a crud(plesase give me an example)? all the relations are many to many

0 likes
1 reply
SilenceBringer's avatar

@m24mohammadi for my mind, pivot with more than 2 foreign keys becomes separated model. Something like AdvertiseFieldValue

this way Advertise, Value and Field will hasMany AdvertiseFieldValue, and AdvertiseFieldValue will belongsTo all 3 models

this way you'll be able to eager load all relations, like

Advertise::with('advertiseFieldValues.field', 'fadvertiseFieldValues.value))->first();

or

Field::with('advertiseFieldValues.advertise', 'advertiseFieldValues.value))->first();
1 like

Please or to participate in this conversation.