【问题标题】:Laravel 'where' collection method modifies the collectionLaravel 'where' 集合方法修改集合
【发布时间】:2016-04-18 22:50:32
【问题描述】:

Laravel where收集方法会修改收集吗?

Laravel documentation,您可以阅读:

几乎每个方法都会返回一个新的 Collection 实例,让您可以保留该集合的原始副本

只有transformforget有修改集合警告的方法

但我有这个代码:

    $descriptions = Description::where('description', $request->description);

    if ($descriptions->count()) {
        $descriptionsWithSameUnit = $descriptions->where('unit_id', $request->unit);
        if ($descriptionsWithSameUnit->count()==0) {
            $descriptionsWithAnotherUnit = $descriptions->where('unit_id', '!=', $request->unit);
            if ($descriptionsWithAnotherUnit->count()) {
        ...

并且集合在第一个 where 之后被修改,所以 $descriptionsWithAnotherUnit 始终为空,因为此时集合只有 unit_id == $request->unit 的记录。这是框架还是文档中的错误?

从这里产生的问题是:我可以做些什么来保留原始对象的副本而不从数据库中再次检索?我试过这个:

$descriptions = Description::where('description', $request->description);

if ($descriptions->count()) {
    $descriptionsWithSameUnit = $descriptions;
    $descriptionsWithSameUnit->where('unit_id', $request->unit);
    ...

但是当我将where 方法应用于$descriptionsWithSameUnit 对象时,$descriptions 对象也被修改了

【问题讨论】:

    标签: laravel laravel-5 laravel-5.2 laravel-collection


    【解决方案1】:

    首先要获取收藏,你需要使用get,所以如果你想获取收藏,你应该这样做:

    $descriptions = Description::where('description', $request->description)->get();
    

    不仅如此:

    $descriptions = Description::where('description', $request->description);
    

    第二件事是在收集时不可能使用where method 的运算符,所以:

    $descriptionsWithAnotherUnit = $descriptions->where('unit_id', '!=', $request->unit);
    

    完全不正确。你应该在这里使用filtermethod。

    【讨论】:

    • Aaaahhh 现在我明白了,我使用的是 Eloquent where 方法,没有集合。谢谢,我没看到。
    • @MariaVilaró 没问题。你看到的那些方法和 Eloquent 的方法不一样
    猜你喜欢
    • 2017-03-26
    • 2012-04-11
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2019-02-09
    相关资源
    最近更新 更多