I have no idea what all of the terminology means in the Laravel/Eloquent docs for relationships like hasOne or belongsTo.
The hasOne class has the properties $parent, $related, $foreignKey, and $localKey among others.
The belongsTo class has the properties $parent, $related, $child, $foreignKey, and $ownerKey among others.
I wish I had a cheat sheet that had example relationships like
Given a one to one relationship between users and phones: user hasOne phone. phone belongsTo user hasOne class properties: $parent = a $related = b $foreignKey = c $localKey = d ... maybe more hasOne properties here belongsTo class properties: $parent = a $related = b $child = c $foreignKey = d $ownerKey = e ... maybe more belongsTo properties here
Except with a, b, c, d, etc filled in.
I’d love have these kinds of examples for all relationship types. hasMany class properties and belongsToMany class properties in one to many and many to many relationships, etc. Every combination.
The following quote (which is probably wrong) from my notes highlights a confusion I have:
"if a hasOne b or a hasMany b: a is called the parent model and b is called the related model, but I think b is also called the child model, so idk." – I’m pretty sure this quote is wrong, but I wish I knew the distinction between the different terms like child model and related model, etc.
2
Answers
I ended up testing everything for the hasOne and belongsTo cases. Results are below.
Eloquent’s APIs are harder to understand once you’re trying to fill in all the variables and what they do. I’m going to re-use Laravel’s example of User having phones as you used it with all of the given code filled in.
Given a
User
model with anid
and aPhone
model with anid
and auser_id
, the two functions would look like this:User.php:
In which case,
$parent
is the current User model (e.g User id 1)$related
is the phone that this user has (e.g Phone id 1)$foreignKey
is the key you have inside your Phone model (e.guser_id
)$local_key
is the key that you have in your local / current model which is User in this case.the same goes for the reverse:
Phone.php
the same above is still true except now you have
owner_key
instead oflocal_key
, it still refers to the key in the original / parent model.I have to admit that I’m not sure what the
$child
property does though I wouldn’t worry about it if I was beginning my Laravel journey since there’s no "end-user" use case that I’ve seen for it since Laravel 5.x.