将原始查询转换为Eloquent查询

时间:2018-04-03 14:23:35

标签: mysql laravel eloquent

我试图获得与我在eloquent中使用原始查询已经收到的相同结果。这是我的表格如下:

id  sent_by message         read    received_by created_at  updated_at  

1       7   Hello Mam hello 1           1       2018-04-03 16:53:56 2018-04-03 18:20:47 
2       6   Hello Mam hello 1           1       2018-04-03 16:54:12 2018-04-03 18:20:35 
3       7   Hello Mam hello 1           1       2018-04-03 16:54:21 2018-04-03 18:20:47 
4       7   Hello Mam hello 1           1       2018-04-03 16:55:34 2018-04-03 18:20:47 
7       6   Hello Mam hello 1           1       2018-04-03 17:34:02 2018-04-03 18:20:35 
8       6   Hello Mam hello 0           1       2018-04-03 19:21:03 2018-04-03 19:21:03 

我有这个原始查询已经适合我:

SELECT * FROM `en_chat_message` 
WHERE id IN (SELECT MAX(id) AS id
             FROM `en_chat_message`  
             WHERE received_by=1 OR sent_by=1
             GROUP BY sent_by) 
ORDER BY created_at DESC

从这里我的输出如下:

id sent_by message read received_by created_at updated_at

8       6   Hello Mam hello     0           1       2018-04-03 19:21:03 2018-04-03 19:21:03 
4       7   Hello Mam hello     1           1       2018-04-03 16:55:34 2018-04-03 18:20:47 

现在我唯一想要将此查询转换为雄辩查询。我没有得到与执行模型名称相关的想法。

谢谢! (提前)

2 个答案:

答案 0 :(得分:1)

使用查询构建器:

DB::table('en_chat_message')
    ->whereIn('id', function($query) {
        $query->selectRaw('MAX(id) id')
            ->from('en_chat_message')
            ->where('received_by', 1)
            ->orWhere('sent_by', 1)
            ->groupBy('sent_by');
    })
    ->orderByDesc('created_at')
    ->get();

使用Eloquent模型:

class EnChatMessage extends \Illuminate\Database\Eloquent\Model
{
    protected $table = 'en_chat_message';
}

EnChatMessage::whereIn('id', function($query) {
    $query->selectRaw('MAX(id) id')
        ->from('en_chat_message')
        ->where('received_by', 1)
        ->orWhere('sent_by', 1)
        ->groupBy('sent_by');
    })
    ->orderByDesc('created_at')
    ->get();

答案 1 :(得分:0)

Chat::select(DB::raw('SELECT MAX(id) AS id, sent_by, message, read, received_by, created_at, updated_at'))
                ->where('received_by', 1)
                ->orWhere('sent_by', 1)
                ->groupBy('sent_by')
                ->orderBy('created_at', 'desc')
                ->get();