【问题标题】:Yii Indirect modification of overloaded propertyYii 对重载属性的间接修改
【发布时间】:2011-07-17 06:40:57
【问题描述】:
$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();

我收到错误:

重载的间接修改 属性 Bids::$seller 无效 (/var/www/auction/www/protected/models/Bids.php:16)

但在另一台服务器上一切正常吗? 如何解决?或者覆盖php指令?有任何想法吗? TNX

【问题讨论】:

    标签: php activerecord yii


    【解决方案1】:

    这里的问题是$seller 不是一个“真实的”属性(Yii 通过使用神奇的__get 方法在其模型上实现属性),因此实际上您正在尝试修改函数的返回值(没有效果)。就好像你试图这样做:

    function foo() {
        return 42;
    }
    
    // INVALID CODE FOR ILLUSTRATION
    (foo())++;
    

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

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

    【讨论】:

    • Tnx,用于响应。但现在我收到致命错误:在第 1 行的 /var/www/auction/www/protected/models/Bids.php 中调用未定义的方法 stdClass::save()
    • @Joeeee:那么$this->seller 不是它应该是的对象——显然它应该是CActiverRecord 的某个子类,但它不是(可能是null)。您需要对此进行调查。
    • @joeeee 有几种方法可以纠正这个问题... a) 不要偷懒:$this->seller->current_item = $this->seller->current_item + 1; b) 使用 setAttribute: $this->seller->setAttribute( $this->seller->current_item + 1 ) c) 使用 AR 的计数器:$this->卖家->updateCounters(array('current_item'=>1,'wins'=>1)) 希望有帮助!
    【解决方案2】:

    当我尝试使用 CActiveRecord 属性属性大规模操作属性时,我还收到错误消息 “Yii 间接修改重载属性”

    然后,我发现了另一种解决此问题的方法,在魔术方法与包含数组的对象变量相关的情况下,请查看:创建一个辅助数组,将原始值和新值放入其中(有时想要替换与其中一个键相关的值,这些方法并不令人满意)。 AFTERWARDS 使用分配,其工作方式类似于参考。例如:

    $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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 2012-03-02
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多