According to Laravel 5 documentation,
Eloquent will automatically determine the proper foreign key column on the Comment model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.
This, however, is not the case in reality, because if one has:
// Class: Video
public function author()
{
return $this->belongsTo('App\User');
}
then calling $video->author will not work, because Laravel will assume the foreign key to be author_id instead of user_id.
Am I missing anything or is this indeed a documentation error?
You are posting the documentation for hasMany
, not belongsTo
.
For belongsTo
it will look for user_id
in the Video and match it against id
on the User model. For hasMany
it will look for the id
in Video and match it against video_id
in User, which makes no sense in this case.
belongsTo
is the inverted version of hasMany
.
EDIT: Yes. Sorry, you seem to be right. When I change the relationship function's name to user
instead of author
it works.
The only way to get around it easily is to pass user_id
along as foreign key.
// Video
public function author()
{
return $this->belongsTo('App\User', 'user_id');
}
However, the documentation for belongsTo
does state (You posted hasMany
):
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method
As I said in my original answer, you were looking at the incorrect part of the documentation.