合并两个Eloquent集合,并删除所有重复项. [英] Merge two Eloquent Collections and remove all duplicates.

查看:107
本文介绍了合并两个Eloquent集合,并删除所有重复项.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,$user_roles$global_roles.我想创建一个新数组,我们称之为$available_roles,在这里它可以等同于$global_roles中的项目减去$user_roles

I have two arrays, $user_roles and $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_roles less the items in the $user_roles

我有以下代码可以对普通数组进行处理. $available_roles = array_unique(array_merge($global_roles, $user_roles), SORT_REGULAR);

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

这被证明是有问题的,因为当Laravel执行查询时,它不使用传统数组,而是使用了Eloquent Collections.

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.

你们还有什么其他想法?

What other ideas do you guys have?

推荐答案

这很简单.您可以使用集合的merge方法:

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

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

由于merge在内部使用以id为键的关联数组(字典),因此应自动删除重复项.

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

尽管如此,您仍然可以使用unique删除集合中的重复项:

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

$uniqueCollection = $collection->unique();


现在,要用于合并的是,您实际上正在寻找的是两个集合之间的差异.您可以通过两种方式执行此操作:


Now that was for merging what you're actually are looking for is the difference between two collections. You can do this in two ways:

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

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

这篇关于合并两个Eloquent集合,并删除所有重复项.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆