如何将复杂的SQL查询转换为laravel Eloquent

德鲁夫·拉瓦尔(Dhruv Raval)

这个工作最好。但我想雄辩地转换成laravel。谁能帮助我。我不知道如何在laravel中使用join。

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");
德鲁夫·拉瓦尔(Dhruv Raval)

转换后的laravel Eloquen:

$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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章