forked from mootensai/yii2-relation-trait
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRelationTrait.php
221 lines (209 loc) · 9.03 KB
/
RelationTrait.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
<?php
/**
* RelationTrait
*
* @author Yohanes Candrajaya <moo.tensai@gmail.com>
* @since 1.0
*/
namespace mootensai\relation;
use \yii\db\ActiveRecord;
use \yii\db\Exception;
use \yii\helpers\Inflector;
use \yii\helpers\StringHelper;
trait RelationTrait {
public function loadAll($POST) {
if ($this->load($POST)) {
$shortName = StringHelper::basename(get_class($this));
foreach ($POST as $key => $value) {
if ($key != $shortName && strpos($key, '_') === false) {
$isHasMany = is_array($value);
$relName = ($isHasMany) ? lcfirst($key) . 's' : lcfirst($key);
$rel = $this->getRelation($relName);
$relModelClass = $rel->modelClass;
$relPKAttr = $relModelClass::primaryKey();
if ($isHasMany) {
$container = [];
foreach ($value as $relPost) {
/* @var $relObj ActiveRecord */
$relObj = (empty($relPost[$relPKAttr[0]])) ? new $rel->modelClass : $relModelClass::findOne($relPost[$relPKAttr[0]]);
$relObj->load($relPost, '');
$container[] = $relObj;
}
$this->populateRelation($relName, $container);
} else {
$relObj = new $rel->modelClass;
$relObj->load($value);
$this->populateRelation($relName, $value);
}
}
}
return true;
} else {
return false;
}
}
public function saveAll() {
/* @var $this ActiveRecord */
$db = $this->getDb();
$trans = $db->beginTransaction();
try {
if ($this->save()) {
$error = 0;
foreach ($this->relatedRecords as $name => $records) {
$AQ = $this->getRelation($name);
$link = $AQ->link;
$notDeletedPK = [];
$relPKAttr = $records[0]->primaryKey();
$isCompositePK = (count($relPKAttr) > 1);
/* @var $relModel ActiveRecord */
foreach ($records as $index => $relModel) {
$notDeletedFK = [];
foreach ($link as $key => $value) {
$relModel->$key = $this->$value;
$notDeletedFK[$key] = "$key = '{$this->$value}'";
}
$relSave = $relModel->save();
if (!$relSave || !empty($relModel->errors)) {
$relModelWords = Inflector::camel2words(StringHelper::basename($AQ->modelClass));
$index++;
foreach ($relModel->errors as $validation) {
foreach ($validation as $errorMsg) {
$this->addError($name, "$relModelWords #$index : $errorMsg");
}
}
$error = 1;
} else {
//GET PK OF REL MODEL
if ($isCompositePK) {
foreach ($relModel->primaryKey as $attr => $value) {
$notDeletedPK[$attr][] = "'$value'";
}
} else {
$notDeletedPK[] = "'$relModel->primaryKey'";
}
}
}
if (!$this->isNewRecord) {
//DELETE WITH 'NOT IN' PK MODEL & REL MODEL
$notDeletedFK = implode(' AND ', $notDeletedFK);
if ($isCompositePK) {
$compiledNotDeletedPK = [];
foreach ($notDeletedPK as $attr => $pks) {
$compiledNotDeletedPK[$attr] = "$attr NOT IN(" . implode(', ', $pks) . ")";
if (!empty($compiledNotDeletedPK[$attr])) {
$relModel->deleteAll("$notDeletedFK AND " . implode(' AND ', $compiledNotDeletedPK));
}
}
} else {
$compiledNotDeletedPK = implode(',', $notDeletedPK);
if (!empty($compiledNotDeletedPK)) {
$relModel->deleteAll($notDeletedFK . ' AND ' . $relPKAttr[0] . " NOT IN ($compiledNotDeletedPK)");
}
}
}
}
if ($error) {
$trans->rollback();
return false;
}
$trans->commit();
return true;
} else {
return false;
}
} catch (Exception $exc) {
$trans->rollBack();
throw $exc;
}
}
public function deleteWithRelated() {
/* @var $this ActiveRecord */
$db = $this->getDb();
$trans = $db->beginTransaction();
try {
$error = 0;
$relData = $this->getRelationData();
foreach ($relData as $data) {
if($data['ismultiple']){
$AQ = $this->getRelation($data['name']);
$link = $AQ->link;
if(count($this->{$data['name']})){
$relPKAttr = $this->{$data['name']}[0]->primaryKey();
$isCompositePK = (count($relPKAttr) > 1);
foreach ($link as $key => $value) {
if(isset($this->$value)){
$array[$key] = $key . ' = ' . $this->$value;
}
}
$error = !$this->{$data['name']}[0]->deleteAll(implode(' AND ', $array));
}
}
}
if ($error) {
$trans->rollback();
return false;
}
if($this->delete()){
$trans->commit();
return true;
}
$trans->rollBack();
} catch (Exception $exc) {
$trans->rollBack();
throw $exc;
}
}
public function getRelationData() {
$ARMethods = get_class_methods('\yii\db\ActiveRecord');
$modelMethods = get_class_methods('\yii\base\Model');
$reflection = new \ReflectionClass($this);
$i = 0;
$stack = [];
/* @var $method \ReflectionMethod */
foreach ($reflection->getMethods() as $method) {
if (in_array($method->name, $ARMethods) || in_array($method->name, $modelMethods)) {
continue;
}
if($method->name === 'bindModels') {continue;}
if($method->name === 'attachBehaviorInternal') {continue;}
if($method->name === 'loadAll') {continue;}
if($method->name === 'saveAll') {continue;}
if($method->name === 'getRelationData') {continue;}
if($method->name === 'getAttributesWithRelatedAsPost') {continue;}
if($method->name === 'getAttributesWithRelated') {continue;}
if($method->name === 'deleteWithRelated') {continue;}
try {
$rel = call_user_func(array($this,$method->name));
if($rel instanceof \yii\db\ActiveQuery){
$stack[$i]['name'] = lcfirst(str_replace('get', '', $method->name));
$stack[$i]['method'] = $method->name;
$stack[$i]['ismultiple'] = $rel->multiple;
$i++;
}
} catch (\yii\base\ErrorException $exc) {}
}
return $stack;
}
/* this function is deprecated */
public function getAttributesWithRelatedAsPost() {
$return = [];
$shortName = StringHelper::basename(get_class($this));
$return[$shortName] = $this->attributes;
foreach ($this->relatedRecords as $records) {
foreach ($records as $index => $record) {
$shortNameRel = StringHelper::basename(get_class($record));
$return[$shortNameRel][$index] = $record->attributes;
}
}
return $return;
}
public function getAttributesWithRelated() {
$return = $this->attributes;
foreach ($this->relatedRecords as $name => $records) {
foreach ($records as $index => $record) {
$return[$name][$index] = $record->attributes;
}
}
return $return;
}
}