【发布时间】:2020-08-14 17:22:37
【问题描述】:
更新
我有一条使用 Yii 插入的记录
我的模型名为 Shipment,实现了:
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => BlameableBehavior::className(),
],
[
'class' => TimestampBehavior::className(),
],
];
}
假设这些是数据库中的记录,如下所示:
DATABASE (1:1)
+----+--------------------+--------------------+------------+------------+
| id | freight_created_at | freight_updated_at | created_at | updated_at |
+----+--------------------+--------------------+------------+------------+
| XX | NULL | NULL | 1597223608 | 1597315472 |
+----+--------------------+--------------------+------------+------------+
然后我需要更新另一个名为 freight_created_at & freight_updated_at 的列。这是因为在同一条记录中,所以我不能再次使用 EVENT_BEFORE_INSERT。
我对PUT货运的行动,目标是:
- 如果
freight_created_at栏为空,请填写freight_created_at和freight_updated_at - 其他人只更新
freight_updated_at
然后在 Yii2 中
控制器
public function actionPutFreightDitawarkan($id) {
$model = $this->findModel($id);
$model->scenario = Shipment::SCENARIO_FREIGHT_DITAWARKAN;
$model->attachBehaviors([FreightDitawarkanTimestamp::class]);
...
}
如果我想使用一个行为,我该如何实现它?到目前为止,行为看起来像这样。
行为
class FreightDitawarkanTimestamp extends AttributeBehavior {
public $createdAtAttribute = 'freight_created_at';
public $updatedAtAttribute = 'freight_updated_at';
public $value;
public function init() {
if (empty($this->attributes)) {
$this->attributes = [
BaseActiveRecord::EVENT_BEFORE_UPDATE =>
[
$this->createdAtAttribute,
$this->updatedAtAttribute
]
];
}
parent::init();
}
protected function getValue($event) {
$this->value = date('Y-m-d H:i');
return parent::getValue($event);
}
}
【问题讨论】: