简体   繁体   中英

Laravel 5.7. Subtract model instances

I have 2 collections of models.

For example

$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',
    ],
]);

and I want to receive such a result after something like this

$full->diff($full);

$result = [
    [
        'name' => 'name2',
    ],
    [
        'name' => 'name3',
    ],
];

How to achieve that without filter() or reject() with contains() in a neater way?

The diff method should work as needed with a new collection containing just the name property:

$comparableDiff = $diff->pluck('name');
$result = $full->diff($comparableDiff);

It's hard to say why you don't want to use filter or reject with contains but there is another solution:

$result = $full->pluck('name')->diff($diff->pluck('name'))->map(function($name) {
        return [
            'name' => $name
        ];
    });

dd($result->toArray());

As result you will get:

array:2 [▼
  1 => array:1 [▼
    "name" => "name2"
  ]
  2 => array:1 [▼
    "name" => "name3"
  ]
]

I haven't found a neater approach than

$profiles->reject(function ($profile) use ($existingProfiles) {
    return $existingProfiles->pluck('name')->contains($profile->name);
})->values()

But thanks to everyone. I've upvoted your questions ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM