Laravel query builders : Join the same table twice

Posted 8 months ago by hamedgasemi200

I wanted to get posts by liked-post (like_post table) tags

let me make an example, Imagine you like a post on a website, This website has to show you related posts based on that post tags

I wrote this following code but the problem is when I get tags from liked posts, I want to find other posts that have the same tags!

$posts = DB::table('post_like')
    ->where(['like' => 1, 'post_like.user_id' => Auth::user()->id])
    ->join('post_tag', function ($join) {
        $join->on('post_tag.post_id', '!=', 'post_like.post_id');
    })
    ->get();

Returns liked posts tags

This is what I really want, But it causes an error

$posts = DB::table('post_like')
    ->where(['like' => 1, 'post_like.user_id' => Auth::user()->id])
    ->join('post_tag', function ($join) {
        $join->on('post_tag.post_id', '!=', 'post_like.post_id');
    })
    ->join('post_tag', function ($join) {
        $join->on('post_tag.tag_id', '!=', 'post_tag.tag_id');
    })
    ->get();

I'll be appreciated if you could answer my question.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.