laravel 合并两个 Eloquent Collections 并删除所有重复项。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29446255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:17:29  来源:igfitidea点击:

Merge two Eloquent Collections and remove all duplicates.

arrayslaravelcollectionseloquent

提问by Rijnhardt

I have two arrays, $user_rolesand $global_roles. I want to make a new array, let's call it $available_roles, where it can be equated as the items in $global_rolesless the items in the $user_roles

我有两个数组,$user_roles$global_roles. 我想创建一个新数组,我们称之为$available_roles,它可以等同$global_roles$user_roles

I have the following code to do it to a normal array. $available_roles = array_unique(array_merge($global_roles, $user_roles), SORT_REGULAR);

我有以下代码可以对普通数组执行此操作。 $available_roles = array_unique(array_merge($global_roles, $user_roles), SORT_REGULAR);

This is proving to be problematic due to the fact that Laravel does not use traditional arrays when one executes a query, it uses Eloquent Collections.

这被证明是有问题的,因为 Laravel 在执行查询时不使用传统数组,而是使用 Eloquent 集合。

What other ideas do you guys have?

大家还有什么想法?

回答by lukasgeiter

This is fairly simple. You can use the Collection's mergemethod:

这相当简单。您可以使用集合的merge方法:

$available_roles = $global_roles->merge($user_roles);

Because mergeinternally uses an associative array (dictionary) that uses the id as key, this should automatically remove duplicates.

因为在merge内部使用一个关联数组(字典),它使用 id 作为键,这应该会自动删除重复项。

Anyways though, you can remove duplicates in a collection using unique:

无论如何,您可以使用unique以下方法删除集合中的重复项:

$uniqueCollection = $collection->unique();


Now that was for mergingwhat you're actually are looking for is the differencebetween two collections. You can do this in two ways:

现在这是为了合并您实际要寻找的两个集合之间的差异。您可以通过两种方式执行此操作:

$available_roles = $user_roles->diff($global_roles);

or

或者

$available_roles = $global_roles->except($user_roles->modelKeys());