lundi 29 juin 2015

Laravel 5: Convert raw SQL using WhereIn to Eloquent

Hope you can help me converting this raw sql because the converted one I have is not working.

Raw SQL

$connected = DB::select(DB::raw('SELECT count(*)
    FROM users
    WHERE
        id != '.$id.'
        AND id IN (SELECT from_user FROM connections WHERE to_user = '.$id.' AND status = 3)
        OR id IN (SELECT to_user FROM connections WHERE from_user = '.$id.' AND status = 3)
'));

SQL Converted to Eloquent

$connected  = User::whereIn('id', function($q) use ($id) {
    $q->select('connections.from_user');
    $q->where('connections.to_user', $id);
    $q->where('connections.status',3);
})
->orWhereIn('id', function($q) use ($id) {
    $q->select('connections.to_user');
    $q->where('connections.from_user',   $id);
    $q->where('connections.status',3);
})
->count();

Aucun commentaire:

Enregistrer un commentaire