在Laravelcollection的objects到return的键上使用搜索功能?

Use search function on a Laravel collection of objects to return the key?

一般来说,我试图从 object 的 laravel collection 中删除 object。我不希望将 collection 转换为数组来执行此任务,因为这会使首先使用 collection 的任何真正理由无效。我也不希望从数据库中删除基础模型 - 我只是希望从 collection.

中删除记录

查看文档中的可用方法,我没有找到完成此任务的简单方法。

LaravelCollections有个variety of methods. The search method看起来很有前途,

The search method searches the collection for the given value and returns its key if found.

我打算将返回的密钥与 forget method 一起使用来处理不需要的 object。

The forget method removes an item from the collection by its key

但是,我能找到的每个“搜索”方法示例都只使用简单的 collection 整数或字符串来显示功能。我希望在 collection.

中包含的 object 中搜索

我们有以下变量:

$coll // a collection of objects taken from a database.  
            // Each object contains a field called "invoice_number" that I am trying to match.

$invoice_number // the invoice number associated with the object
                // I wish to remove from $coll

$tmp_object = $coll->firstWhere('invoice_number', $invoice_number);  // the needle for the haystack

感谢使用 collections 找到问题解决方案的任何帮助,尤其是使用“搜索”方法。

谢谢。

您可以使用 filter:

$res = $coll->filter(function($el) use($invoice_number){
    return $el->invoice_number != $invoice_number;
});

您可以使用“过滤”方法:

$coll = $coll->filter(function($invoice) use ($invoice_number){
return $invoice->invoice_number != $invoice_number;
});

如果您的 invoice_number 是独一无二的,您可以这样做:

$coll = $coll->keyBy('invoice_number');

$coll[$invoice_number];

检索它并

$coll->forget($invoice_number);

仅将其从您的 collection

中删除