代码之家  ›  专栏  ›  技术社区  ›  Dhruv Raval

如何将复杂的SQL查询转换为Laravel雄辩的

  •  1
  • Dhruv Raval  · 技术社区  · 6 年前

    这是最好的工作。但我想转变为拉拉维尔雄辩。有人能帮我吗?我不知道如何使用Join in in Laravel。

    DB::select("SELECT u.id,c.conversation_key,u.user_name,u.email
                                     FROM conversation c, user_profile u
                                     WHERE CASE 
                                     WHEN c.user_one = '8790'
                                     THEN c.user_two = u.id
                                     WHEN c.user_two = '8790'
                                     THEN c.user_one= u.id
                                     END 
                                     AND (
                                     c.user_one ='8790'
                                     OR c.user_two ='8790'
                                     )
                                     Order by c.conversation_key DESC Limit 20");
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Dhruv Raval    6 年前

    转换后的Laravel口才:

    $userId = 8790;
    $data['conversations'] = Conversation::selectRaw('user_profile.id, conversation_key, user_profile.first_name, user_profile.email')
                ->where(function ($q) use ($userId) {
                    $q->where('user_one', $userId)
                        ->orWhere('user_two', $userId);
                })
                ->join('user_profile', function ($join) use ($userId) {
                    $join->on('user_profile.id', '=', 'conversation.user_one')->where('conversation.user_one', '!=', $userId)
                        ->orOn('user_profile.id', '=', 'conversation.user_two')->where('conversation.user_two', '!=', $userId);
                })
                ->orderBy('conversation_key', 'DESC')
                ->take(20)
                ->get();