Yii重载属性的间接修改

bttbmeg0  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(156)
$winnerBid = Bids::model()->find($criteria);

模型具有下一个关系:

public function relations() {
        return array(
            'item' => array(self::BELONGS_TO, 'Goods', 'item_id'),
            'room' => array(self::BELONGS_TO, 'Rooms', 'room_id'),
            'seller' => array(self::BELONGS_TO, 'RoomPlayers', 'seller_id'),
            'buyer' => array(self::BELONGS_TO, 'RoomPlayers', 'buyer_id'),
        );
    }

当我尝试保存时:

$this->seller->current_item++;
    $this->seller->wins++;
    $this->seller->save();

出现错误:
间接修改超载的属性投标::$卖方没有效果(/var/www/auction/www/protected/models/Bids.php:16)

但是在另一个服务器上一切都很好?如何修复?或者覆盖php指令?有什么想法吗?TNX

yr9zkbsy

yr9zkbsy1#

这里的问题是$seller不是一个“真实的”属性(Yii通过使用神奇的__get方法实现了它的Model属性),所以实际上你试图修改一个函数的返回值(这没有任何效果)。

function foo() {
    return 42;
}

// INVALID CODE FOR ILLUSTRATION
(foo())++;

我不确定这种行为在不同PHP版本上的状态,但有一个简单的变通方法可以用途:

$seller = $this->seller;
$seller->current_item++;
$seller->wins++;
$seller->save();
sczxawaw

sczxawaw2#

当我尝试使用CActiveRecord属性来大量操作属性时,我也收到了错误消息**“Yii Indirect modification of overloaded property”**。
然后,我发现了另一种方法来克服这个问题,在一个例子中,魔术方法与一个包含数组的对象变量有关,请看一下:你创建一个AUXILIARY ARRAY,在其中放入原始值和新值(有时候你想替换与某个键相关的值,这些方法并不令人满意)。AFTERVARDS使用赋值,它的工作方式类似于引用。例如:

$auxiliary_array = array();
foreach(Object->array_built_with_magic as $key=>$value) {
     if(….) {
      $auxiliary_array[$key] = Object->array_built_with_magic[$key];
      } else if (…) {
      $auxiliary_array[$key] = $NEW_VALUE
      }
}
//So now we have the array $auxiliary_array with the
// desired MIX (that is, some originals, some modifications)
//So we will do now:
Object->array_built_with_magic =$auxiliary_array;
9wbgstp7

9wbgstp73#

我在升级到php8.1的时候遇到了这个错误,它是在createCommand()方法中。
而且在以前的php版本中,它也没有抱怨我们访问了模型上的一个属性,而这个属性还没有初始化。
解决方法是将bindParam()方法更改为bindValue()
因为前者要使用对应的数据库字段,而数据库字段还没有初始化,而后者(bindParam)只是在sql语句中插入值。

相关问题