Posts Learn Components Snippets Categories Tags About
/

Laravel with relationship but use join syntax

Learn how to get model relationship in laravel but using join instead

Created on Aug 06, 2021

19 views

Query Relationship using with()
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.

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Laravel with relationship but use join syntax

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More