获取用户的 DISTINCT id 并找到他们列的最大值然后更新,LARAVEL
Get the DISTINCT id of users and find the MAX of their column then UPDATE, LARAVEL
我想做的是,distinct
id
基于关联列的 max
值,然后 update
相应的列。
例如
id | name | total | description | updateThis
1 | john | 100 | example | 0
2 | dave | 300 | example | 0
2 | johno | 500 | example | 0
4 | derik | 900 | example | 0
5 | Sam | 1000 | example | 0
4 | bool | 12200 | example | 0
1 | john | 1200 | example | 0
5 | john | 300 | example | 0
我希望它看起来像这样:
id | name | total | description | updateThis
1 | john | 1200 | example | 1
2 | johno | 500 | example | 1
4 | bool | 12200 | example | 1
5 | Sam | 1000 | example | 1
我使用的是 Query Builder 而不是 eloquent 的方法,这两种方法都是有用的答案,如果有人能给出这两种方法,那就太棒了,我只需要帮助,谢谢。
你可以使用这个:
$rows = DB::table('table')
->select('id', DB::raw('max(total) as total'))
->groupBy('id')
->get();
foreach($rows as $row) {
DB::table('table')
->where('id', $row->id)
->where('total', $row->total)
->update(['updateThis' => 1]);
}
我想做的是,distinct
id
基于关联列的 max
值,然后 update
相应的列。
例如
id | name | total | description | updateThis
1 | john | 100 | example | 0
2 | dave | 300 | example | 0
2 | johno | 500 | example | 0
4 | derik | 900 | example | 0
5 | Sam | 1000 | example | 0
4 | bool | 12200 | example | 0
1 | john | 1200 | example | 0
5 | john | 300 | example | 0
我希望它看起来像这样:
id | name | total | description | updateThis
1 | john | 1200 | example | 1
2 | johno | 500 | example | 1
4 | bool | 12200 | example | 1
5 | Sam | 1000 | example | 1
我使用的是 Query Builder 而不是 eloquent 的方法,这两种方法都是有用的答案,如果有人能给出这两种方法,那就太棒了,我只需要帮助,谢谢。
你可以使用这个:
$rows = DB::table('table')
->select('id', DB::raw('max(total) as total'))
->groupBy('id')
->get();
foreach($rows as $row) {
DB::table('table')
->where('id', $row->id)
->where('total', $row->total)
->update(['updateThis' => 1]);
}