Home / Snippets / Laravel with relationship but use join syntax
Laravel with relationship but use join syntax cover

Laravel with relationship but use join syntax

268

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this