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