如何选择user_id的每个option_id的最新版本?
+-----+-----------+---------+-------+
| id | option_id | user_id | value |
+-----+-----------+---------+-------+
| 241 | 6 | 2 | 2 |
| 240 | 5 | 2 | 1 |
| 90 | 5 | 2 | 15 |
| 75 | 4 | 2 | 11 |
| 76 | 4 | 2 | 1 |
| 77 | 4 | 2 | 2 |
| 72 | 4 | 1 | 10 |
| 71 | 4 | 1 | 15 |
| 70 | 5 | 1 | 2 |
+-----+-----------+---------+-------+
如何使用Eloquent编写查询以仅实现给定user_id的每个option_id的最新内容?
对于提供的表,user_id 2的输出应为记录id:241,240,75。
对于user_id 1记录:72,70
编辑:
为了重新迭代,我想为给定的user_id返回最新的option_id的集合。
因此对于user_id 2,将有3条记录:
对于user_id 1,仅有2条记录:
假设该表是User,并且考虑到$id
是动态的。也许你的意思是:
$user = User::where('user_id', $id)
->orderBy('id', 'DESC')
->get();
最后使用此代码$user->unique('option_id')
来获得实际结果。
如果您的表名为user_options,则此处是Eloquent查询,用于选择您要查找的记录。
$getValues = DB::table('user_options')
->join(DB::raw('(SELECT max(user_options.id) FROM user_options INNER JOIN (
SELECT option_id, user_id FROM user_options GROUP BY option_id, user_id) sets
WHERE user_options.option_id = sets.option_id AND user_options.user_id = sets.user_id
GROUP BY user_options.option_id, user_options.user_id
) valuerecords'),
function($join)
{
$join->on('user_options.id', '=', 'valuerecords.id');
})->select(
'id',
'option_id',
'user_id',
'value'
)->get();
原始选择查询获取最新记录的ID,然后将其连接回表以获取记录。
请注意,“最新”记录是具有最高ID的记录,因此它将获取记录77而不是75.如果您以不同方式定义最新记录,则可以相应地更改原始查询。
事实证明它很简单:
$options= DB::table('options')
->where('user_id', Auth::getUser()->id)
->groupBy("option_id")
->orderBy("option_id", "DESC")
->get();
但是,一旦检索到数据,就不得不为此查询将严格模式设置为false并将其恢复为true。
在查询之前:
// turn off strict mode for the below query
config()->set('database.connections.mysql.strict', false);
\DB::reconnect(); //important as the existing connection if any would be in strict mode
并在查询之后:
//now changing back the strict ON
config()->set('database.connections.mysql.strict', true);
\DB::reconnect();