To easily get the model relationship in Laravel, you can make use of the "with()" method of the model class and specify the relationship instance to be retrieved.
<?php $post = Post::with('comments')->first(); dd($post->comments); // get all of the comments relation
But the query above has some downside which is querying the database twice since it's retrieving the "posts" table first and then the "comments" table relation. In big-scale applications, the code above will be inefficient.
Query Relationship using Join
To replicate the query code like above but only querying the database once, then you can write it using the join clause.
<?php $post = Post::join('comments', 'posts.comment_id', '=', 'comments.id')->first(); dd($post->comments);
By writing it like above it's much more efficient and you will get the same result as using the "with()" method.
Leave a reply