Laravel 集合 where 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44473906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:06:57  来源:igfitidea点击:

Laravel collection where clause

phplaravelcollections

提问by Mintendo

Is possible in Laravel apply where condition to a collection and the result of that put in another collection without change the first one?

在 Laravel 中是否可以将 where 条件应用于集合并将结果放入另一个集合而不更改第一个集合?

Ex:

前任:

$documenti = DB::table("RVW_DocumentiDettaglio")
                ->select("*")
                ->where("IDAzienda", "=", $request->session()->get("operatore.IDAzienda"))
                ->whereIn("CodiceStato", [Documento::E_DOC, Documento::W_DOC, Documento::OK_DOC])
                ->orderBy("IDDocumentoTestata", "asc");

// Ciclo le voci spesa
foreach ($voci_spesa as $voce_spesa) {
    Log_Controller::debug("Documenti:" . $documenti->get());

    if ($voce_spesa["Manuale"]) {
        $dettaglio = $documenti->where("Descrizione", "like", "%" . $voce_spesa["Descrizione"] . "%");
    } else {
        $dettaglio = $documenti->where("Descrizione", "=", $voce_spesa["Descrizione"]);
    }
    Log_Controller::debug("Dettaglio:" . $dettaglio->get());
}
die;

With $documentiI get the first collection, in the foreach I apply the where condition and put the result to $dettagliocollection, but the first one ($documenti) was also changed. Why? It's like shared object

随着$documenti我得到的第一个系列,在foreach我适用where语句,并把结果$dettaglio集,但第一个($documenti)也被改变了。为什么?这就像共享对象

回答by

You can certainly apply where clauses to Collections along with a good number of other methods including filtering and mapping. See the documentation here:

您当然可以将 where 子句以及许多其他方法(包括过滤和映射)应用于集合。请参阅此处的文档:

Collections where clauses

集合 where 子句

$collection = Item::all();

$filtered = $collection->where('price', 100);

$filtered->all();