有没有办法在 laravel 中加入两个集合?

Is there a way to join two collections in laravel?

假设我有一个从 HTTP 请求中检索到的数组:

$request['sports'] => [0 => 'basketball', 1 => 'bowling', 2 => 'Tennis'];

然后,在我的数据库中我检索了这个集合:

$sports = [0 => 'basketball', 1 => 'bowling', 3 => 'boxing']

laravel 中是否有一个函数可以删除数据库中的“拳击”运动,因为它在 HTTP 请求的集合中找不到。 “网球”将被添加到数据库中,因为它包含在 HTTP 请求的集合中。没有针对“篮球”和“保龄球”的操作,因为它们都在请求和数据库中找到?

$input = collect(['basketball', 'bowling', 'Tennis']);
$database = collect(['basketball', 'bowling', 'boxing']);

$added = $input->diff($database);
$removed = $database->diff($input);

$database->concat($added)->diff($removed);

// ['basketball', 'bowling', 'Tennis'];

您可以使用 collect() 帮助程序从数组创建集合,然后过滤所需的元素 - 一个数组中而不是另一个数组中的元素。这是一个例子:

    $request['sports'] = [0 => 'basketball', 1 => 'bowling', 2 => 'Tennis'];
    $db = [0 => 'basketball', 1 => 'bowling', 3 => 'boxing'];

    // create collections
    $requestCollection = collect($request['sports']);
    $dbCollection = collect($db);

    // filter items from db colection, that are not in request collection
    $toDelete = $dbCollection->filter(function ($item) use ($requestCollection) {
        return !$requestCollection->contains($item);
    })->each(function ($item){
        // todo: delete them
    });
    // filter items from request colection, that are not in db collection
    $toAdd = collect($requestCollection)->filter(function ($item) use ($dbCollection) {
        return !$dbCollection->contains($item);
    })->each(function ($item){
        // todo: add them
    });

    dd($toDelete, $toAdd);

dd 将打印出:

Illuminate\Support\Collection {#1953
  #items: array:1 [
    3 => "boxing"
  ]
}
Illuminate\Support\Collection {#1954
  #items: array:1 [
    2 => "Tennis"
  ]
}