0

I'm trying to change the following query to laravel :

SELECT 
*


FROM
usrusrs uu
,posts p


WHERE 
(
uu.user_id = $u_id
or
uu.friend_id = $u_id
)
and
(
uu.user_id = p.user_id
OR
uu.friend_id = p.user_id  
)    

I tried the following, but it's giving different output. I think there might be something wrong with the joining between the two tables. any suggestions ?

           $usrusrmembs = DB::table('usrusrs')
                    ->join('posts', 'posts.user_id', '=', 'usrusrs.user_id')
                    ->orwhere('posts.user_id', '=', 'usrusrs.friend_id')
                    ->where('usrusrs.user_id', $u_id)
                    ->orwhere('usrusrs.friend_id', $u_id)                   
                    ->get();
4
  • 1
    Wherever you see (x OR y) in your query, you need to do a ->where(function($query) { $query->where(x); $query->orWhere(y); }) to enclose the set in parentheses. Commented Aug 3, 2019 at 14:33
  • You'll also want to consider using Laravel relationships instead of a join. It'll make a lot of Laravel things easier. Commented Aug 3, 2019 at 14:34
  • @ceejayoz, I'm not sure how to do the join part using the method you mentioned. Commented Aug 3, 2019 at 14:44
  • Your User model would have a function posts() { return $this->hasMany(Post::class); }, which allows you to do things like $user->posts and User::whereHas('posts'). (That's the basics; far more complicated setups/queries are 100% possible.) laravel.com/docs/5.8/eloquent-relationships Commented Aug 3, 2019 at 14:59

1 Answer 1

1

Got it after some digging :

      $usrusrmembs = DB::table('usrusrs')
                ->join('posts', function ($join) {
                   $join->on('posts.user_id', '=', 'usrusrs.user_id')->orOn('posts.user_id', '=', 'usrusrs.friend_id');
                    })
                ->where('usrusrs.user_id', $u_id)
                ->orwhere('usrusrs.friend_id', $u_id)                   
                ->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.