为了简化问题,当我遍历雄辩查询返回的对象数组时,当我试图更改它的一个属性时,它似乎正在更改所有属性。
假设fruit是雄辩查询返回的数据
var fruits =[{name:apple,nested_relationship:{price:$5},{name:pear,{price:$6},{name:grape}]
foreach ($fruits as fruit){
if($fruit->name == 'apple'){
$fruit->nested_relationship->color = 'red';
}
elseif($fruit->name == 'grape'){
$fruit->nested_relationship->color = 'green';
}
}
最后的结果似乎是[{name:'apple',nested_relationship:{price:$5,color:'green'}},{name:pear,nested_relationship:{price:$5,color:'green'}},},{name:'grape'}]
试试这个解决方案:
使用setAttribute()添加新属性。
var fruits =[{name:apple,nested_relationship:{price:$5},{name:pear,{price:$6},{name:grape}]
foreach ($fruits as $fruit){
if($fruit->name == 'apple'){
$fruit->nested_relationship->setAttribute('color', 'red');
}
elseif($fruit->name == 'grape'){
$fruit->nested_relationship->setAttribute('color', 'green');
}
}