Yii间接修改重载属性

Joe*_*eee 14 php activerecord yii

$winnerBid = Bids::model()->find($criteria);
Run Code Online (Sandbox Code Playgroud)

模型有下一个关系:

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'),
        );
    }
Run Code Online (Sandbox Code Playgroud)

当我想保存时:

 $this->seller->current_item++;
    $this->seller->wins++;
    $this->seller->save();
Run Code Online (Sandbox Code Playgroud)

我收到错误:

间接修改超载属性投标:: $卖方无效(/var/www/auction/www/protected/models/Bids.php:16)

但是在另一台服务器上一切都很好吗?怎么解决?或者覆盖php指令?有任何想法吗?TNX

Jon*_*Jon 18

这里的问题是它$seller不是一个"真正的"属性(Yii通过使用魔术__get方法在其模型上实现属性),所以实际上你试图修改一个函数的返回值(它没有任何效果).就像你试图做的那样:

function foo() {
    return 42;
}

// INVALID CODE FOR ILLUSTRATION
(foo())++;
Run Code Online (Sandbox Code Playgroud)

我不确定这种行为在不同PHP版本上的状态,但是您可以使用以下简单的解决方法:

$seller = $this->seller;
$seller->current_item++;
$seller->wins++;
$seller->save();
Run Code Online (Sandbox Code Playgroud)

  • @joeeee夫妻纠正这个方法... a)不要懒惰:`$ this-> seller-> current_item = $ this-> seller-> current_item + 1;`b)使用`setAttribute`:`$ this - > seller-> setAttribute($ this-> seller-> current_item + 1)`c)使用AR的计数器:$ this-> seller-> updateCounters(array('current_item'=> 1,'wins'=> 1) ))希望有所帮助! (4认同)