Laravel - Relationships - One To Many Inverse
Now that we can access all of a post's comments, let's define a relationship to allow a comment to access its parent post. To define the inverse of a hasMany
relationship, define a relationship method on the child model which calls the belongsTo
method:
belongsTo(Post::class);
}
}
Once the relationship has been defined, we can retrieve a comment's parent post by accessing the post
"dynamic relationship property":
use App\Models\Comment;
$comment = Comment::find(1);
return $comment->post->title;
In the example above, Eloquent will attempt to find a Post
model that has an id
which matches the post_id
column on the Comment
model.
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _
followed by the name of the parent model's primary key column. So, in this example, Eloquent will assume the Post
model's foreign key on the comments
table is post_id
.
However, if the foreign key for your relationship does not follow these conventions, you may pass a custom foreign key name as the second argument to the belongsTo
method:
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo(Post::class, 'foreign_key');
}
If your parent model does not use id
as its primary key, or you wish to find the associated model using a different column, you may pass a third argument to the belongsTo
method specifying your parent table's custom key:
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo(Post::class, 'foreign_key', 'owner_key');
}