-
Notifications
You must be signed in to change notification settings - Fork 0
/
MetaBehavior.php
executable file
·67 lines (58 loc) · 1.4 KB
/
MetaBehavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
/**
* Created by PhpStorm.
* User: yidashi
* Date: 16/7/21
* Time: 上午12:35
*/
namespace common\behaviors;
use common\models\Meta;
use common\traits\EntityTrait;
use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
class MetaBehavior extends Behavior
{
use EntityTrait;
public function events()
{
return [
ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete'
];
}
public function afterSave()
{
if (\Yii::$app->request->isConsoleRequest ) {
return;
}
$model = $this->getMetaModel();
if ($model->load(Yii::$app->request->post())) {
$model->save();
}
}
public function afterDelete()
{
$this->getMetaModel()->delete();
}
public function getMetaModel()
{
$model = $this->owner->meta;
if ($model == null) {
$model = new Meta([
'entity' => $this->getEntity(),
'entity_id' => $this->getEntityId()
]);
}
return $model;
}
public function getMeta()
{
return $this->owner->hasOne(Meta::className(), [
'entity_id' => $this->owner->primaryKey()[0]
])->where([
"entity" => $this->getEntity()
]);
}
}