Php演示了如何在一个条件之外获得唯一的值



我的表格中有这样的内容:

id |MIT_ID| type| date | updated_at|
1  | 1    | 2  | ...   | ....     |
2  | 1    |1  | ...  |  ...     |
3  | 1    |3  | ...  |  ...     |
4  | 1    |4  | ...  |  ...     |
5  | 1    |4  | ...  |  ...     |
6  | 1    |2  | ...  |  ...     |
7  | 1    |2  | ...  |  ...     |

,我想订购update_at和获得unique_values旁边的类型2,所以所有其他应该只返回一个值,但类型2应该得到两行。我尝试这样做:

$entry = User::orderBy('updated_at','DESC')->where('MIT_ID', '=', $MIT_ID)->get();
$entry = $entry->unique('type_id');
or using distinct didnt work neither.
Desired values:
id| type| date | updated_at|
1  |  2  | ...   | ....     |
2  | 1  | ...  |  ...     |
3  | 3  | ...  |  ...     |
4  | 4  | ...  |  ...     |
6  | 2  | ...  |  ...     |

有办法吗?其他所有东西都是独一无二的,但只有一个值不是吗?

提前感谢!

You can use following methods to get unique values:
using Group By
$entry = User::orderBy('updated_at','DESC')->where('MIT_ID', '=', 
$MIT_ID)->groupBy('type_id')->get();
Using Distinct
$entry = User::orderBy('updated_at','DESC')->where('MIT_ID', '=', 
$MIT_ID)->distinct('type_id')->get();
using pluck
$entry = User::orderBy('updated_at','DESC')->where('MIT_ID', '=', 
$MIT_ID)->pluck('type_id')->get();
#####Altered#####
$entry = User::orderBy('updated_at','DESC')->where('MIT_ID', '=', 
$MIT_ID)->get();
$entry->map(function($e) use $isRepeat {
if( ($e->type_id!=2 & $isRepeat ==1) OR ($e->type_id ==2 and $isRepeat < 2)){
return $e;   }
});

相关内容

最新更新