php 间接修改重载元素没有效果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27853928/
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-08-25 23:33:44  来源:igfitidea点击:

Indirect modification of overloaded element has no effect

phpeloquent

提问by eComEvo

I have the following Eloquent query:

我有以下雄辩的查询:

$item = Item::where('sku', $sku)->first();

After this query comes in I'm adding a variety of elements manually such as:

在这个查询进来后,我手动添加了各种元素,例如:

$item['total'] = $item['subtotal'] + $this->currentInventory();

Statements like the above that modify the object work just fine.

像上面修改对象的语句工作得很好。

It stops working when I do the following:

当我执行以下操作时它停止工作:

$item['fields'] = [];

$fields = DB::table('item_fields')->where('item_id', $item['id'])->get();

foreach ($fields as $f) {
    if (!isset($item['fields'][$f->field_group_name]))
         $item['fields'][$f->field_group_name] = [];

    $item['fields'][$f->field_group_name]['valid_values'] = DB::table('item_field_valid_values')->where('item_field_id', $f->item_field_id);
}

This will cause the line $item['fields'][$f->field_group_name] = [];to produce the error:

这将导致该行$item['fields'][$f->field_group_name] = [];产生错误:

Indirect modification of overloaded element of Item has no effect

How can it be that I can assign $item['fields'] = []but when I try to add an actual element to the $item['fields']array that I get this error?

我怎么能分配$item['fields'] = []但是当我尝试将实际元素添加到$item['fields']数组时出现此错误?

PHP version 5.6.0.

PHP 版本 5.6.0。

采纳答案by Jarek Tkaczyk

First off, you're missing get()in your code, so either:

首先,您get()的代码中缺少,因此:

1You are iterating over the Query\Builderinstead of the array of results, because you never executed the query. (I suppose you forgot it only here, because otherwise you would probably get trying to get property of non-object)

1您正在迭代Query\Builder而不是结果数组,因为您从未执行过查询。(我想你只是在这里忘记了它,否则你可能会得到trying to get property of non-object

or 2one of the rows has ''or nullvalue in the field_group_namecolumn.

2行之一在列中具有''nullfield_group_name

That's why your code does this:

这就是为什么您的代码会这样做:

$item['fields'][NULL] = [];

and that's causing Indirect modification ...error.

这导致Indirect modification ...错误。

So add check for empty value first:

所以首先添加检查空值:

if ($f->field_group_name && ! isset($item['fields'][$f->field_group_name]))
     $item['fields'][$f->field_group_name] = [];

you may need to adjust it to your needs, but you get the idea.

您可能需要根据自己的需要对其进行调整,但您明白了。