【问题标题】:Laravel Eloquent Collection remove item from Collection if exist in arrayLaravel Eloquent Collection 如果存在于数组中,则从 Collection 中删除项目
【发布时间】:2022-01-18 22:42:22
【问题描述】:

我今天遇到了一个简单的问题。我在 Livewire 组件中工作,我有一个对象集合,当我单击一个对象时,我想将它添加到一个数组中(有效),然后想从集合中删除它 - 所以那个对象不是可点击了。 我有什么:

public function addPartToUsage($partId){
    $partToAdd = Part::where('id', '=', $partId)->first();

    $this->verwendung[] = ['id'=> $partToAdd->id, 'partBezeichnung'=>$partToAdd->id.':'.$partToAdd->zeichnungsnummer.' - '.$partToAdd->artikelbezeichnung];

    $this->partsClient = Part::where('artikelbezeichnung', 'LIKE', '%' . $this->inputsearchpart . '%')
        ->orWhere('zeichnungsnummer', 'LIKE', '%' . $this->inputsearchpart . '%')
        ->orderBy('artikelnummer')
        ->get();



    foreach ($this->verwendung as $item) {

        if($this->partsClient->contains('id', $item['id'])){
          
           $this->partsClient->forget($this->partsClient->where('id', $item['id'])->id);
        }  }  }

但它不起作用,因为我不知道包含匹配 id 的元素的键。

$this->verwendung 是我的数组,其中包含 $this->verwendung[0]['id'] 中的 id 和 $this->partsClient 是我的集合,来自数据库。

如何修改集合而不将其转换为数组,然后检查匹配的 ID,然后重新收集? 或者更好的是如何检索集合的匹配键,以便我可以使用 forget() ? 感谢这里的所有人!

【问题讨论】:

    标签: laravel collections


    【解决方案1】:

    你可以直接用reject()过滤而不是检查集合中是否包含id

    foreach ($this->verwendung as $item) {
        $this->partsClient->reject(function ($value, $key) use ($item) {
            return $value->id == $item['id'];
        });
    }
    

    或者干脆

    $verwendungCollection = collect($this->verwendung);
    
    $idsToRemove = $verwendungCollection->pluck('id')->toArray();
    
    $this->partsClient->reject(function ($value, $key) use ($item) {
        return in_array($value->id, $idsToRemove);
    });
    
    

    【讨论】:

    • 嗨 N69S,我不会工作 :( - 我已经在我的代码中实现了这两个版本,但集合中仍然充满了所有对象。所以我测试了这段代码:我用值填充了我的数组并创建了一个集合并尝试使用 reject() 过滤集合 - 集合保持不变:(
    • ` $this->verwendung[] = ['id' => 4, 'partBezeichnung' => 'bez']; $this->verwendung[] = ['id' => 55, 'partBezeichnung' => 'bez2']; $checkarr[] = ['id' => 12, 'partBezeichnung' => 'bez12']; $checkarr[] = ['id' => 13, 'partBezeichnung' => 'bez13']; $checkarr[] = ['id' => 4, 'partBezeichnung' => 'bez4']; $checkColl = 收集($checkarr); foreach ($this->verwendung as $item) { $checkColl->reject(function ($value, $key) use ($item) { return $value['id'] === $item['id'] ; }); } dd($checkColl);`
    • 我错过了什么?抱歉评论代码我不知道如何在 cmets 中正确格式化它
    • 好的,请删除我的 cmets ...我已经在 tinker 中对其进行了测试,它按预期工作。我的错 - 我的组件有错误,我不知道在哪里 :) 但我离终点更近了一小步 :) Thx - N69S
    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多