|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
|
|
4
|
|
|
namespace Arrilot\BitrixModels\Queries; |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
use Arrilot\BitrixModels\Helpers; |
|
8
|
|
|
use Arrilot\BitrixModels\Models\BaseBitrixModel; |
|
9
|
|
|
use Illuminate\Support\Collection; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* BaseRelationQuery содержит основные методы и свойства для загрузки релейшенов |
|
13
|
|
|
* |
|
14
|
|
|
* @method BaseBitrixModel first() |
|
15
|
|
|
* @method Collection|BaseBitrixModel[] getList() |
|
16
|
|
|
* @property array $select |
|
17
|
|
|
*/ |
|
18
|
|
|
trait BaseRelationQuery |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @var bool - когда запрос представляет связь с один-ко-многим. Если true, вернуться все найденные модели, иначе только первая |
|
22
|
|
|
*/ |
|
23
|
|
|
public $multiple; |
|
24
|
|
|
/** |
|
25
|
|
|
* @var string - настройка связи моделей. ключ_у_связанной_модели |
|
26
|
|
|
*/ |
|
27
|
|
|
public $foreignKey; |
|
28
|
|
|
/** |
|
29
|
|
|
* @var string - настройка связи моделей. ключ_у_текущей_модели |
|
30
|
|
|
*/ |
|
31
|
|
|
public $localKey; |
|
32
|
|
|
/** |
|
33
|
|
|
* @var BaseBitrixModel - модель, для которой производится загрузка релейшена |
|
34
|
|
|
*/ |
|
35
|
|
|
public $primaryModel; |
|
36
|
|
|
/** |
|
37
|
|
|
* @var array - список связей, которые должны быть подгружены при выполнении запроса |
|
38
|
|
|
*/ |
|
39
|
|
|
public $with; |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Найти связанные записи для определенной модели [[$this->primaryModel]] |
|
43
|
|
|
* Этот метод вызывается когда релейшн вызывается ленивой загрузкой $model->relation |
|
44
|
|
|
* @return Collection|BaseBitrixModel[]|BaseBitrixModel - связанные модели |
|
45
|
|
|
* @throws \Exception |
|
46
|
|
|
*/ |
|
47
|
|
|
public function findFor() |
|
48
|
|
|
{ |
|
49
|
|
|
return $this->multiple ? $this->getList() : $this->first(); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Определяет связи, которые должны быть загружены при выполнении запроса |
|
54
|
|
|
* |
|
55
|
|
|
* Передавая массив можно указать ключем - название релейшена, а значением - коллбек для кастомизации запроса |
|
56
|
|
|
* |
|
57
|
|
|
* @param array|string $with - связи, которые необходимо жадно подгрузить |
|
58
|
|
|
* // Загрузить Customer и сразу для каждой модели подгрузить orders и country |
|
59
|
|
|
* Customer::query()->with(['orders', 'country'])->getList(); |
|
60
|
|
|
* |
|
61
|
|
|
* // Загрузить Customer и сразу для каждой модели подгрузить orders, а также для orders загрузить address |
|
62
|
|
|
* Customer::find()->with('orders.address')->getList(); |
|
63
|
|
|
* |
|
64
|
|
|
* // Загрузить Customer и сразу для каждой модели подгрузить country и orders (только активные) |
|
65
|
|
|
* Customer::find()->with([ |
|
66
|
|
|
* 'orders' => function (BaseQuery $query) { |
|
67
|
|
|
* $query->filter(['ACTIVE' => 'Y']); |
|
68
|
|
|
* }, |
|
69
|
|
|
* 'country', |
|
70
|
|
|
* ])->all(); |
|
71
|
|
|
* |
|
72
|
|
|
* @return $this |
|
73
|
|
|
*/ |
|
74
|
|
|
public function with($with) |
|
75
|
|
|
{ |
|
76
|
|
|
$with = is_string($with) ? func_get_args() : $with; |
|
77
|
|
|
|
|
78
|
|
|
if (empty($this->with)) { |
|
79
|
|
|
$this->with = $with; |
|
80
|
|
|
} elseif (!empty($with)) { |
|
81
|
|
|
foreach ($with as $name => $value) { |
|
82
|
|
|
if (is_int($name)) { |
|
83
|
|
|
// дубликаты связей будут устранены в normalizeRelations() |
|
84
|
|
|
$this->with[] = $value; |
|
85
|
|
|
} else { |
|
86
|
|
|
$this->with[$name] = $value; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|
|
91
|
|
|
return $this; |
|
92
|
|
|
} |
|
93
|
|
|
|
|
94
|
|
|
/** |
|
95
|
|
|
* Добавить фильтр для загрзуки связи относительно моделей |
|
96
|
|
|
* @param Collection|BaseBitrixModel[] $models |
|
97
|
|
|
*/ |
|
98
|
|
|
protected function filterByModels($models) |
|
99
|
|
|
{ |
|
100
|
|
|
$values = []; |
|
101
|
|
|
foreach ($models as $model) { |
|
102
|
|
|
if (($value = $model[$this->foreignKey]) !== null) { |
|
103
|
|
|
if (is_array($value)) { |
|
104
|
|
|
$values = array_merge($values, $value); |
|
105
|
|
|
} else { |
|
106
|
|
|
$values[] = $value; |
|
107
|
|
|
} |
|
108
|
|
|
} |
|
109
|
|
|
} |
|
110
|
|
|
|
|
111
|
|
|
$values = array_filter($values); |
|
112
|
|
|
if (empty($values)) { |
|
113
|
|
|
$this->stopQuery(); |
|
|
|
|
|
|
114
|
|
|
} |
|
115
|
|
|
|
|
116
|
|
|
$primary = $this->localKey; |
|
117
|
|
|
if (preg_match('/^PROPERTY_(.*)_VALUE$/', $primary, $matches) && !empty($matches[1])) { |
|
118
|
|
|
$primary = 'PROPERTY_' . $matches[1]; |
|
119
|
|
|
} |
|
120
|
|
|
$values = array_unique($values, SORT_REGULAR); |
|
121
|
|
|
if (count($values) == 1) { |
|
122
|
|
|
$values = current($values); |
|
123
|
|
|
} else { |
|
124
|
|
|
$this->prepareMultiFilter($primary, $values); |
|
|
|
|
|
|
125
|
|
|
} |
|
126
|
|
|
|
|
127
|
|
|
$this->filter([$primary => $values]); |
|
|
|
|
|
|
128
|
|
|
$this->select[] = $primary; |
|
129
|
|
|
} |
|
130
|
|
|
|
|
131
|
|
|
/** |
|
132
|
|
|
* Подгрузить связанные модели для уже загруденных моделей |
|
133
|
|
|
* @param array $with - массив релейшенов, которые необходимо подгрузить |
|
134
|
|
|
* @param Collection|BaseBitrixModel[] $models модели, для которых загружать связи |
|
135
|
|
|
*/ |
|
136
|
|
|
public function findWith($with, &$models) |
|
137
|
|
|
{ |
|
138
|
|
|
// --- получаем модель, на основании которой будем брать запросы релейшенов |
|
139
|
|
|
$primaryModel = $models->first(); |
|
|
|
|
|
|
140
|
|
|
if (!$primaryModel instanceof BaseBitrixModel) { |
|
141
|
|
|
$primaryModel = $this->model; |
|
|
|
|
|
|
142
|
|
|
} |
|
143
|
|
|
|
|
144
|
|
|
$relations = $this->normalizeRelations($primaryModel, $with); |
|
145
|
|
|
/* @var $relation BaseQuery */ |
|
146
|
|
|
foreach ($relations as $name => $relation) { |
|
147
|
|
|
$relation->populateRelation($name, $models); |
|
|
|
|
|
|
148
|
|
|
} |
|
149
|
|
|
} |
|
150
|
|
|
|
|
151
|
|
|
/** |
|
152
|
|
|
* @param BaseBitrixModel $model - модель пустышка, чтобы получить запросы |
|
153
|
|
|
* @param array $with |
|
154
|
|
|
* @return BaseQuery[] |
|
155
|
|
|
*/ |
|
156
|
|
|
private function normalizeRelations($model, $with) |
|
157
|
|
|
{ |
|
158
|
|
|
$relations = []; |
|
159
|
|
|
foreach ($with as $name => $callback) { |
|
160
|
|
|
if (is_int($name)) { // Если ключ - число, значит в значении написано название релейшена |
|
161
|
|
|
$name = $callback; |
|
162
|
|
|
$callback = null; |
|
163
|
|
|
} |
|
164
|
|
|
|
|
165
|
|
|
if (($pos = strpos($name, '.')) !== false) { // Если есть точка, значит указан вложенный релейшн |
|
166
|
|
|
$childName = substr($name, $pos + 1); // Название дочернего релейшена |
|
167
|
|
|
$name = substr($name, 0, $pos); // Название текущего релейшена |
|
168
|
|
|
} else { |
|
169
|
|
|
$childName = null; |
|
170
|
|
|
} |
|
171
|
|
|
|
|
172
|
|
|
if (!isset($relations[$name])) { // Указываем новый релейшн |
|
173
|
|
|
$relation = $model->getRelation($name); // Берем запрос |
|
174
|
|
|
$relation->primaryModel = null; |
|
175
|
|
|
$relations[$name] = $relation; |
|
176
|
|
|
} else { |
|
177
|
|
|
$relation = $relations[$name]; |
|
178
|
|
|
} |
|
179
|
|
|
|
|
180
|
|
|
if (isset($childName)) { |
|
181
|
|
|
$relation->with[$childName] = $callback; |
|
182
|
|
|
} elseif ($callback !== null) { |
|
183
|
|
|
call_user_func($callback, $relation); |
|
184
|
|
|
} |
|
185
|
|
|
} |
|
186
|
|
|
|
|
187
|
|
|
return $relations; |
|
188
|
|
|
} |
|
189
|
|
|
/** |
|
190
|
|
|
* Находит связанные записи и заполняет их в первичных моделях. |
|
191
|
|
|
* @param string $name - имя релейшена |
|
192
|
|
|
* @param array $primaryModels - первичные модели |
|
193
|
|
|
* @return Collection|BaseBitrixModel[] - найденные модели |
|
194
|
|
|
*/ |
|
195
|
|
|
public function populateRelation($name, &$primaryModels) |
|
196
|
|
|
{ |
|
197
|
|
|
$this->filterByModels($primaryModels); |
|
198
|
|
|
|
|
199
|
|
|
$models = $this->getList(); |
|
200
|
|
|
|
|
201
|
|
|
Helpers::assocModels($primaryModels, $models, $this->foreignKey, $this->localKey, $name, $this->multiple); |
|
202
|
|
|
|
|
203
|
|
|
return $models; |
|
204
|
|
|
} |
|
205
|
|
|
} |
|
206
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.