How to join 3 tables using laravel eloquent?

by herminia_bruen , in category: PHP Frameworks , 4 months ago

How to join 3 tables using laravel eloquent?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 4 months ago

@herminia_bruen 

To join 3 tables using Laravel Eloquent, you can use the with method to eager load relationships. Here is an example of how you can join 3 tables using Laravel Eloquent:


Assume you have 3 models: User, Post, and Comment.


User Model:

1
2
3
4
5
6
7
class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}


Post Model:

1
2
3
4
5
6
7
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}


Comment Model:

1
2
3
class Comment extends Model
{
}


Now, you can join the 3 tables users, posts, and comments using the following query:

1
$users = User::with('posts.comments')->get();


This query will retrieve all users along with their posts and comments. The with method will eager load the relationships between the models.