dongwuzun4630 2016-03-14 12:56
浏览 40

Laravel不同的联接基于何处

So basically what I' trying to do is grab all the friends to a given user, but not grab the given user itself, only the friends. But I got stuck when I needed to have different joins, based on where's. Example:

If the given user is equal to user_id_sender, I would like join tables on user_id_receiver. And the other way around. I came up with this:

DB::table('friends') -> where('friends.user_id_sender', $user_id)
        -> orWhere('friends.user_id_receiver', $user_id)
        -> join('profiles as profile_receiver', 'profile_receiver.user_id', '=', 'friends.user_id_sender')
        -> join('profiles as profile_sender', 'profile_sender.user_id', '=', 'friends.user_id_receiver')
        -> join('users as receiver', 'receiver.id', '=', 'friends.user_id_sender')
        -> join('users as sender', 'sender.id', '=', 'friends.user_id_receiver')
        -> select('receiver.name', 'receiver.id', 'profile_receiver.picture', 'sender.name', 'sender.id', 'profile_sender.picture', 'sender.last_seen', 'receiver.last_seen')
        -> get();

I have only 2 users currently (admin, and user). If I try to view the friends of admin, I see admin (and that is not right, i would like to see user on admin friends and admin on user friends).

I have also tried to use joins inside where clauses, but I found out that doesn't work. I Could do two queries like so, but I would like 1 query only:

$friends1 = DB::table('friends') -> where('friends.user_id_sender', $user_id)
        -> join('profiles', 'profiles.user_id', '=', 'friends.user_id_receiver')
        -> join('users', 'users.id', '=', 'friends.user_id_receiver')
        -> select('users.name', 'profiles.picture', 'users.id')
        -> get();

    $friends2 = DB::table('friends') -> where('friends.user_id_receiver', $user_id)
        -> join('profiles', 'profiles.user_id', '=', 'friends.user_id_sender')
        -> join('users', 'users.id', '=', 'friends.user_id_sender')
        -> select('users.name', 'profiles.picture', 'users.id')
        -> get();

How would I do this?

My database table that contains all the friendships looks like this: enter image description here

  • 写回答

1条回答 默认 最新

  • dowe98261 2016-03-14 15:29
    关注

    Basically there are two ways this could me done that is whenever someone accepts the friend request posting two rows that it once user_sender_id = friend and user_id_receiver = you and next time user_sender_id = you and user_id_receiver = ur friend and next is having two queries.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)