- Messages
- 27
- Likes
- 6
- Trophy Points
- 5
- Followers
- 2
- Joined
- Mar 17, 2022
The only difference between
Example:
hasOne/hasMany
and belongsTo/belongsToMany
is where the foreign key column is located.hasOne
andhasMany
- you are telling Laravel that this table does not have the foreign key.belongsTo
andbelongsToMany
- you are telling Laravel that this table holds the foreign key that connects it to the other table.
Example:
PHP:
# User.php (Model)
public function address (): HasOne
{
return $this->hasOne(UserAddress::class); // This table does not have the foreign key
}
# UserAddress.php (Model)
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id', 'id'); // This table has the foreign key (user_id)
}