使用附加到ActiveRecord的save()内部行为

时间:2015-02-26 11:08:31

标签: yii2

我有ActiveRecord个实例,附带了许多行为。

其中一个相关模型得到更新(除了owner)。使用updateAttributes()即可,但我想触发更新相关模型的行为,例如TimestampBehaviorBlameableBehaviorLogBehavior(自定义)。

如果我们在模型递归中调用save(),有时必须排除一些行为。

我提出了以下解决方案,但在将行为附加回来时失败了。

$detachedBehaviors = $this->getDetachedBehaviors();

foreach ($model->behaviors as $key => $behavior) {
    if (in_array($behavior::className(), $detachedBehaviors)) {
        $model->detachBehavior($key);
    }
}

$model->save(false, [$this->attribute]);

$model->attachBehaviors($detachedBehaviors);

也许有更好的方法可以做到这一点?

我看到另一种选择:

  1. 以某种方式手动触发所需行为的所需事件。

  2. 使用updateAttributes()代替调用save()

  3. 实际上,我并不想将此逻辑绑定到特定行为,并使其适用于任何更灵活的行为。所以我猜这将是另一种行为。

0 个答案:

没有答案