-2

I am converting a piece of database SQL query to Laravel Eloquent query but it doesn't work.

My code snippet looks like this:

SELECT user_id FROM posts WHERE user_id NOT IN (SELECT id FROM users)

Can someone explain why?

1
  • 3
    What have you tried so far..?
    – Petay87
    Jul 5, 2019 at 13:12

1 Answer 1

3

So assuming you have a Post model, you can try something like this:

Post::select('user_id')->whereNotIn('user_id', User::pluck('id'))->get();
3
  • Thanks for your quick response. With Raw Query, I get 78 records back and that is the correct number but with your specified query and my previous tried queries it only returns 73 records. My theory is that there are 5 ids in the posts table to much! How can I solve that? Jul 5, 2019 at 13:22
  • You can try debugging, I don't have your data, so I don't know what does it return. You can check which ids are returned by dumping the ids from the users table like this dd(User::pluck('id'));.
    – nakov
    Jul 5, 2019 at 13:24
  • This can be potentially be very slow due to loading all id's into memory first. I would suggest using a left outer join or a callback Jul 5, 2019 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.