Eloquent unique() 方法需要 return 最后一项

Eloquent unique() method need to return last item

我正在使用 Eloquent unique() collections 方法来 return 独特的项目。它 return collections 中的第一个唯一项。但是,我需要 returning collections.

中的最后一个唯一项
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
                      ~~~   ~~~

$unique = $collection->unique();

$unique->values()->all()

上面的代码会return // [1, 2, 3, 4]。如您所见,unique() 方法 return 处理第一个 12,而不是最后一个 12

我还可以通过 unique() 方法使用回调。但是,我不知道算法应该如何处理 return 来自 collections.

的最后一个唯一项目

我自己想出来了。此答案适用于和我有相同问题的人:

$diary = Diary::orderBy('id', 'desc')->get()->unique('workId')->values()->all();

return $diary;

在上面,我使用了 orderBy() 方法来更改集合的顺序。 get() 方法将 return 结果作为集合。 unique() 方法用于 return 集合中的唯一项目。 values() 方法 return 是一个新的集合,键重置为连续的整数,all() 方法 return 是完整的集合。