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

Snapey's avatar
Level 122

Remember which table gets foreign key in relationship

I put together a little crib list for the common relationships to help me remember which relationship goes with which foreign key requirement.

I hope this is accurate. Please send any amends

+---------------+-------------+--------------+-------------------------+
|               | self        | other model  | pivot                   |
+===============+=============+==============+=========================+
| hasOne        | no key      | self_id      |                         |
| belongsTo     | other_id    | no key       |                         |
| hasMany       | no key      | self_id      |                         |
| belongsToMany | no key      | no key       | keys for self and other |
+---------------+-------------+--------------+-------------------------+

self is the model you are writing the relationship in and other model is the one you want the relationship with.

1 like
8 replies
ohffs's avatar

Something like this might be a handy addition the the eloquent docs (or possibly the migration ones) on the main laravel site :-)

bashy's avatar

Very nice to remember. Sometimes forget!

1 like
jimmck's avatar

If you use Joins foreign keys are self evident. Pivot tables are used to point to 'pooled data' like Customer by Region and/or Date. In a read more than write database the pivot can be a materialized view. Built with the right indexes and queries it can very fast

1 like

Please or to participate in this conversation.