我有2个模型集合。
例如
$full = collect([
[
'name' => 'name1', //id was omitted intentionally
],
[
'name' => 'name2', //id was omitted intentionally
],
[
'name' => 'name3', //id was omitted intentionally
],
]);
$diff = collect([
[
'id' => 6,
'name' => 'name1',
],
]);
我想在这样的事情之后收到这样的结果
$full->diff($full);
$result = [
[
'name' => 'name2',
],
[
'name' => 'name3',
],
];
如何通过整洁的方式在没有{em> filter()
或reject()
的情况下通过contains()
实现?
答案 0 :(得分:1)
diff方法应该与仅包含name属性的新集合一起工作:
$comparableDiff = $diff->pluck('name');
$result = $full->diff($comparableDiff);
答案 1 :(得分:1)
很难说为什么不希望将filter
或reject
与contains
一起使用,但是还有另一种解决方案:
$result = $full->pluck('name')->diff($diff->pluck('name'))->map(function($name) {
return [
'name' => $name
];
});
dd($result->toArray());
结果,您将得到:
array:2 [▼
1 => array:1 [▼
"name" => "name2"
]
2 => array:1 [▼
"name" => "name3"
]
]
答案 2 :(得分:0)
我没有找到比
更整洁的方法$profiles->reject(function ($profile) use ($existingProfiles) {
return $existingProfiles->pluck('name')->contains($profile->name);
})->values()
但是谢谢大家。我已对您的问题进行了投票;)