0

I have a sql query:

select `id` from `users` 
where (
        select count(*) 
        from `user_event` as `uev` 
        where `uev`.`leader_id` = `users`.`id`
      ) > 1

How can I convert it to Eloquent Laravel?

1 Answer 1

3

Assuming you have set up the relationship you can use the has() method for that:

$users = User::select('id')->has('events', '>', 1)->get();

If you want an array of users ids (since you're only selecting the id) you can also use lists():

$ids = User::has('events', '>', 1)->lists('id');

Since you asked, this would be an alternative method (not tested though)

User::where(DB::raw('1'), '<', function($q){
    $q->from('user_event')
      ->where('user_event.leader_id', 'users.id');
})->get();
Sign up to request clarification or add additional context in comments.

5 Comments

Awesome. Thank you very much !!!. Assuming I don't use has. Do you have any other ways?
You're welcome. Maybe with some raw queries, but that's not really Eloquent anymore ;) I see no reason why not to use has if you're using Eloquent anyways..
I am studying Query Builder and Eloquent so can you give me the raw query to do it. Thanks again for your help.
I got a error: QLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)
Hmm. Okay, then it probably doesn't work that way... If you figure something out feel free to suggest an edit

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.