Search code examples
laraveleloquentlaravel-query-buildereloquent-relationship

Laravel Join Tables with intermediate relations


I have 3 Tables.1) Recent Views 2) posts and 3) users. i need to join these three tables with intermediate relation.

recent table
------------
id
post_id
user_id
date
posts table
-----------
id
user_id
post_title
description
date
users table
-----------
id
username
image
email
date

now what is need to get is all data from recent table where user_id = logged_users_id -> join posts table with recent.post_id = posts.id -> join 'users table' with posts.user_id = users.id. how can i do this with laravel eloquent? can someone help me with this?

Code i have used is:

$contents = RecentView::where('user_id', $loggedUser)
                ->with('posts')
                ->with('user')
                ->paginate(12)
                ->toArray();

but it joins user table with recent.user_id = users.id


Solution

  • $contents = RecentView::where('recent_views.user_id', $loggedUser)
    ->leftJoin('feed_posts','recent_views.post_id','=','feed_posts.id')
    ->leftJoin('users','feed_posts.user_id','=','users.id')
    ->paginate(12)->toArray();
    

    Just check the table name and the rest