How do I do this query with subselect in the Laravel?

Asked

Viewed 4,203 times

0

I tried anyway, but he won’t ride for me SubSelect. I used the method toSql() to confirm and really he does not ride.

SQL

SELECT p.descr,p.dt_hr, (SELECT u1.name FROM users u1 WHERE u1.id = f.id_friend) AS name
FROM friends f JOIN users u ON u.id = f.id_user
               JOIN posts p ON p.id_user = f.id_friend
WHERE u.id = 1
ORDER BY p.dt_hr DESC
  • I tried this query here, but without result. $posts = DB::table('Friends') ->select('Friends.*') ->addSelect(DB::raw("(SELECT U1.name FROM users U1 WHERE U1.id = Friends.id_friend) AS name")) ->Join('users', 'users.id', '=', 'Friends.id_user') ->Join('posts', 'posts.id_user', '=', 'Friends.id_friend') ->select('posts.dt_hr', 'posts.descr', 'name')&#Xa->Where('users.id', $id_user) ->orderby('posts.dt_hr', 'desc') ->get();

  • RESOLVED NOW: $posts = DB::table('Friends') ->select('posts.dt_hr', 'posts.descr', 'name', (DB::raw("(SELECT U1.name FROM users U1.id = Friends.id_friend) AS name")) ->Join('users', 'users.id', '=', 'Friends.id_user') ->Join('posts', 'posts.id_user', '=', 'Friends.id_friend') ->Where('users.id', $id_user) ->orderby('posts.dt_hr', 'desc') ->get();

  • Put as reply @Leonardo ... then ...

1 answer

2


Solved!

$posts = DB::table('friends') 
        ->select('posts.dt_hr', 'posts.descr', 'name',
        (DB::raw("(SELECT u1.name FROM users u1 WHERE u1.id = friends.id_friend) AS name")))
        ->join('users', 'users.id', '=', 'friends.id_user')
        ->join('posts', 'posts.id_user', '=', 'friends.id_friend')
        ->where('users.id', $id_user)
        ->orderBy('posts.dt_hr', 'desc')
        ->get();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.