【问题标题】:Is there a way to join two collections in laravel? [closed]有没有办法在 laravel 中加入两个集合? [关闭]
【发布时间】:2020-09-25 16:41:42
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: php laravel laravel-6


    【解决方案1】:

    您可以使用 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"
      ]
    }
    

    【讨论】:

      【解决方案2】:
      $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'];
      

      【讨论】:

        猜你喜欢
        • 2021-03-24
        • 2016-07-18
        • 2021-11-01
        • 2018-06-03
        • 1970-01-01
        • 2013-03-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-11
        相关资源
        最近更新 更多