1 | <?php |
||||||
2 | /** |
||||||
3 | * @link https://www.yiiframework.com/ |
||||||
4 | * @copyright Copyright (c) 2008 Yii Software LLC |
||||||
5 | * @license https://www.yiiframework.com/license/ |
||||||
6 | */ |
||||||
7 | |||||||
8 | namespace yii\db; |
||||||
9 | |||||||
10 | use yii\base\InvalidConfigException; |
||||||
11 | |||||||
12 | /** |
||||||
13 | * ActiveQuery represents a DB query associated with an Active Record class. |
||||||
14 | * |
||||||
15 | * An ActiveQuery can be a normal query or be used in a relational context. |
||||||
16 | * |
||||||
17 | * ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]]. |
||||||
18 | * Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]]. |
||||||
19 | * |
||||||
20 | * Normal Query |
||||||
21 | * ------------ |
||||||
22 | * |
||||||
23 | * ActiveQuery mainly provides the following methods to retrieve the query results: |
||||||
24 | * |
||||||
25 | * - [[one()]]: returns a single record populated with the first row of data. |
||||||
26 | * - [[all()]]: returns all records based on the query results. |
||||||
27 | * - [[count()]]: returns the number of records. |
||||||
28 | * - [[sum()]]: returns the sum over the specified column. |
||||||
29 | * - [[average()]]: returns the average over the specified column. |
||||||
30 | * - [[min()]]: returns the min over the specified column. |
||||||
31 | * - [[max()]]: returns the max over the specified column. |
||||||
32 | * - [[scalar()]]: returns the value of the first column in the first row of the query result. |
||||||
33 | * - [[column()]]: returns the value of the first column in the query result. |
||||||
34 | * - [[exists()]]: returns a value indicating whether the query result has data or not. |
||||||
35 | * |
||||||
36 | * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]], |
||||||
37 | * [[orderBy()]] to customize the query options. |
||||||
38 | * |
||||||
39 | * ActiveQuery also provides the following additional query options: |
||||||
40 | * |
||||||
41 | * - [[with()]]: list of relations that this query should be performed with. |
||||||
42 | * - [[joinWith()]]: reuse a relation query definition to add a join to a query. |
||||||
43 | * - [[indexBy()]]: the name of the column by which the query result should be indexed. |
||||||
44 | * - [[asArray()]]: whether to return each record as an array. |
||||||
45 | * |
||||||
46 | * These options can be configured using methods of the same name. For example: |
||||||
47 | * |
||||||
48 | * ```php |
||||||
49 | * $customers = Customer::find()->with('orders')->asArray()->all(); |
||||||
50 | * ``` |
||||||
51 | * |
||||||
52 | * Relational query |
||||||
53 | * ---------------- |
||||||
54 | * |
||||||
55 | * In relational context ActiveQuery represents a relation between two Active Record classes. |
||||||
56 | * |
||||||
57 | * Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and |
||||||
58 | * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining |
||||||
59 | * a getter method which calls one of the above methods and returns the created ActiveQuery object. |
||||||
60 | * |
||||||
61 | * A relation is specified by [[link]] which represents the association between columns |
||||||
62 | * of different tables; and the multiplicity of the relation is indicated by [[multiple]]. |
||||||
63 | * |
||||||
64 | * If a relation involves a junction table, it may be specified by [[via()]] or [[viaTable()]] method. |
||||||
65 | * These methods may only be called in a relational context. Same is true for [[inverseOf()]], which |
||||||
66 | * marks a relation as inverse of another relation and [[onCondition()]] which adds a condition that |
||||||
67 | * is to be added to relational query join condition. |
||||||
68 | * |
||||||
69 | * @author Qiang Xue <[email protected]> |
||||||
70 | * @author Carsten Brandt <[email protected]> |
||||||
71 | * @since 2.0 |
||||||
72 | * |
||||||
73 | * @template T of (ActiveRecord|array) |
||||||
74 | * |
||||||
75 | * @phpstan-method T|null one($db = null) |
||||||
76 | * @psalm-method T|null one($db = null) |
||||||
77 | * |
||||||
78 | * @phpstan-method T[] all($db = null) |
||||||
79 | * @psalm-method T[] all($db = null) |
||||||
80 | * |
||||||
81 | * @phpstan-method ($value is true ? (T is array ? self<T> : self<array>) : self<T>) asArray($value = true) |
||||||
82 | * @psalm-method ($value is true ? (T is array ? self<T> : self<array>) : self<T>) asArray($value = true) |
||||||
83 | * |
||||||
84 | * @phpstan-method BatchQueryResult<int, T[]> batch($batchSize = 100, $db = null) |
||||||
85 | * @psalm-method BatchQueryResult<int, T[]> batch($batchSize = 100, $db = null) |
||||||
86 | * |
||||||
87 | * @phpstan-method BatchQueryResult<int, T> each($batchSize = 100, $db = null) |
||||||
88 | * @psalm-method BatchQueryResult<int, T> each($batchSize = 100, $db = null) |
||||||
89 | */ |
||||||
90 | class ActiveQuery extends Query implements ActiveQueryInterface |
||||||
91 | { |
||||||
92 | use ActiveQueryTrait; |
||||||
93 | use ActiveRelationTrait; |
||||||
94 | |||||||
95 | /** |
||||||
96 | * @event Event an event that is triggered when the query is initialized via [[init()]]. |
||||||
97 | */ |
||||||
98 | const EVENT_INIT = 'init'; |
||||||
99 | |||||||
100 | /** |
||||||
101 | * @var string|null the SQL statement to be executed for retrieving AR records. |
||||||
102 | * This is set by [[ActiveRecord::findBySql()]]. |
||||||
103 | */ |
||||||
104 | public $sql; |
||||||
105 | /** |
||||||
106 | * @var string|array|null the join condition to be used when this query is used in a relational context. |
||||||
107 | * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called. |
||||||
108 | * Otherwise, the condition will be used in the WHERE part of a query. |
||||||
109 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||||||
110 | * @see onCondition() |
||||||
111 | */ |
||||||
112 | public $on; |
||||||
113 | /** |
||||||
114 | * @var array|null a list of relations that this query should be joined with |
||||||
115 | */ |
||||||
116 | public $joinWith; |
||||||
117 | |||||||
118 | |||||||
119 | /** |
||||||
120 | * Constructor. |
||||||
121 | * @param string $modelClass the model class associated with this query |
||||||
122 | * @param array $config configurations to be applied to the newly created query object |
||||||
123 | */ |
||||||
124 | 21 | public function __construct($modelClass, $config = []) |
|||||
125 | { |
||||||
126 | 21 | $this->modelClass = $modelClass; |
|||||
127 | 21 | parent::__construct($config); |
|||||
128 | } |
||||||
129 | |||||||
130 | /** |
||||||
131 | * Initializes the object. |
||||||
132 | * This method is called at the end of the constructor. The default implementation will trigger |
||||||
133 | * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end |
||||||
134 | * to ensure triggering of the event. |
||||||
135 | */ |
||||||
136 | 21 | public function init() |
|||||
137 | { |
||||||
138 | 21 | parent::init(); |
|||||
139 | 21 | $this->trigger(self::EVENT_INIT); |
|||||
140 | } |
||||||
141 | |||||||
142 | /** |
||||||
143 | * Executes query and returns all results as an array. |
||||||
144 | * @param Connection|null $db the DB connection used to create the DB command. |
||||||
145 | * If null, the DB connection returned by [[modelClass]] will be used. |
||||||
146 | * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned. |
||||||
147 | * @psalm-return T[] |
||||||
148 | * @phpstan-return T[] |
||||||
149 | */ |
||||||
150 | 4 | public function all($db = null) |
|||||
151 | { |
||||||
152 | 4 | return parent::all($db); |
|||||
153 | } |
||||||
154 | |||||||
155 | /** |
||||||
156 | * {@inheritdoc} |
||||||
157 | */ |
||||||
158 | 12 | public function prepare($builder) |
|||||
159 | { |
||||||
160 | // NOTE: because the same ActiveQuery may be used to build different SQL statements |
||||||
161 | // (e.g. by ActiveDataProvider, one for count query, the other for row data query, |
||||||
162 | // it is important to make sure the same ActiveQuery can be used to build SQL statements |
||||||
163 | // multiple times. |
||||||
164 | 12 | if (!empty($this->joinWith)) { |
|||||
165 | $this->buildJoinWith(); |
||||||
166 | $this->joinWith = null; // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687 |
||||||
167 | } |
||||||
168 | |||||||
169 | 12 | if (empty($this->from)) { |
|||||
170 | 12 | $this->from = [$this->getPrimaryTableName()]; |
|||||
171 | } |
||||||
172 | |||||||
173 | 12 | if (empty($this->select) && !empty($this->join)) { |
|||||
174 | list(, $alias) = $this->getTableNameAndAlias(); |
||||||
175 | $this->select = ["$alias.*"]; |
||||||
176 | } |
||||||
177 | |||||||
178 | 12 | if ($this->primaryModel === null) { |
|||||
179 | // eager loading |
||||||
180 | 11 | $query = Query::create($this); |
|||||
181 | } else { |
||||||
182 | // lazy loading of a relation |
||||||
183 | 1 | $where = $this->where; |
|||||
184 | |||||||
185 | 1 | if ($this->via instanceof self) { |
|||||
186 | // via junction table |
||||||
187 | $viaModels = $this->via->findJunctionRows([$this->primaryModel]); |
||||||
188 | $this->filterByModels($viaModels); |
||||||
189 | 1 | } elseif (is_array($this->via)) { |
|||||
190 | // via relation |
||||||
191 | /** @var self $viaQuery */ |
||||||
192 | list($viaName, $viaQuery, $viaCallableUsed) = $this->via; |
||||||
193 | if ($viaQuery->multiple) { |
||||||
194 | if ($viaCallableUsed) { |
||||||
195 | $viaModels = $viaQuery->all(); |
||||||
196 | } elseif ($this->primaryModel->isRelationPopulated($viaName)) { |
||||||
197 | $viaModels = $this->primaryModel->$viaName; |
||||||
198 | } else { |
||||||
199 | $viaModels = $viaQuery->all(); |
||||||
200 | $this->primaryModel->populateRelation($viaName, $viaModels); |
||||||
201 | } |
||||||
202 | } else { |
||||||
203 | if ($viaCallableUsed) { |
||||||
204 | $model = $viaQuery->one(); |
||||||
205 | } elseif ($this->primaryModel->isRelationPopulated($viaName)) { |
||||||
206 | $model = $this->primaryModel->$viaName; |
||||||
207 | } else { |
||||||
208 | $model = $viaQuery->one(); |
||||||
209 | $this->primaryModel->populateRelation($viaName, $model); |
||||||
210 | } |
||||||
211 | $viaModels = $model === null ? [] : [$model]; |
||||||
212 | } |
||||||
213 | $this->filterByModels($viaModels); |
||||||
214 | } else { |
||||||
215 | 1 | $this->filterByModels([$this->primaryModel]); |
|||||
216 | } |
||||||
217 | |||||||
218 | 1 | $query = Query::create($this); |
|||||
219 | 1 | $this->where = $where; |
|||||
220 | } |
||||||
221 | |||||||
222 | 12 | if (!empty($this->on)) { |
|||||
223 | $query->andWhere($this->on); |
||||||
224 | } |
||||||
225 | |||||||
226 | 12 | return $query; |
|||||
227 | } |
||||||
228 | |||||||
229 | /** |
||||||
230 | * {@inheritdoc} |
||||||
231 | */ |
||||||
232 | 11 | public function populate($rows) |
|||||
233 | { |
||||||
234 | 11 | if (empty($rows)) { |
|||||
235 | 3 | return []; |
|||||
236 | } |
||||||
237 | |||||||
238 | 8 | $models = $this->createModels($rows); |
|||||
239 | 8 | if (!empty($this->join) && $this->indexBy === null) { |
|||||
240 | $models = $this->removeDuplicatedModels($models); |
||||||
241 | } |
||||||
242 | 8 | if (!empty($this->with)) { |
|||||
243 | $this->findWith($this->with, $models); |
||||||
244 | } |
||||||
245 | |||||||
246 | 8 | if ($this->inverseOf !== null) { |
|||||
247 | $this->addInverseRelations($models); |
||||||
248 | } |
||||||
249 | |||||||
250 | 8 | if (!$this->asArray) { |
|||||
251 | 8 | foreach ($models as $model) { |
|||||
252 | 8 | $model->afterFind(); |
|||||
253 | } |
||||||
254 | } |
||||||
255 | |||||||
256 | 8 | return parent::populate($models); |
|||||
257 | } |
||||||
258 | |||||||
259 | /** |
||||||
260 | * Removes duplicated models by checking their primary key values. |
||||||
261 | * This method is mainly called when a join query is performed, which may cause duplicated rows being returned. |
||||||
262 | * @param array $models the models to be checked |
||||||
263 | * @throws InvalidConfigException if model primary key is empty |
||||||
264 | * @return array the distinctive models |
||||||
265 | */ |
||||||
266 | private function removeDuplicatedModels($models) |
||||||
267 | { |
||||||
268 | $hash = []; |
||||||
269 | /** @var ActiveRecord $class */ |
||||||
270 | $class = $this->modelClass; |
||||||
271 | $pks = $class::primaryKey(); |
||||||
272 | |||||||
273 | if (count($pks) > 1) { |
||||||
274 | // composite primary key |
||||||
275 | foreach ($models as $i => $model) { |
||||||
276 | $key = []; |
||||||
277 | foreach ($pks as $pk) { |
||||||
278 | if (!isset($model[$pk])) { |
||||||
279 | // do not continue if the primary key is not part of the result set |
||||||
280 | break 2; |
||||||
281 | } |
||||||
282 | $key[] = $model[$pk]; |
||||||
283 | } |
||||||
284 | $key = serialize($key); |
||||||
285 | if (isset($hash[$key])) { |
||||||
286 | unset($models[$i]); |
||||||
287 | } else { |
||||||
288 | $hash[$key] = true; |
||||||
289 | } |
||||||
290 | } |
||||||
291 | } elseif (empty($pks)) { |
||||||
292 | throw new InvalidConfigException("Primary key of '{$class}' can not be empty."); |
||||||
293 | } else { |
||||||
294 | // single column primary key |
||||||
295 | $pk = reset($pks); |
||||||
296 | foreach ($models as $i => $model) { |
||||||
297 | if (!isset($model[$pk])) { |
||||||
298 | // do not continue if the primary key is not part of the result set |
||||||
299 | break; |
||||||
300 | } |
||||||
301 | $key = $model[$pk]; |
||||||
302 | if (isset($hash[$key])) { |
||||||
303 | unset($models[$i]); |
||||||
304 | } elseif ($key !== null) { |
||||||
305 | $hash[$key] = true; |
||||||
306 | } |
||||||
307 | } |
||||||
308 | } |
||||||
309 | |||||||
310 | return array_values($models); |
||||||
311 | } |
||||||
312 | |||||||
313 | /** |
||||||
314 | * Executes query and returns a single row of result. |
||||||
315 | * @param Connection|null $db the DB connection used to create the DB command. |
||||||
316 | * If `null`, the DB connection returned by [[modelClass]] will be used. |
||||||
317 | * @return array|ActiveRecord|null a single row of query result. Depending on the setting of [[asArray]], |
||||||
318 | * the query result may be either an array or an ActiveRecord object. `null` will be returned |
||||||
319 | * if the query results in nothing. |
||||||
320 | * @psalm-return T|null |
||||||
321 | * @phpstan-return T|null |
||||||
322 | */ |
||||||
323 | 10 | public function one($db = null) |
|||||
324 | { |
||||||
325 | 10 | $row = parent::one($db); |
|||||
326 | 10 | if ($row !== false) { |
|||||
327 | 8 | $models = $this->populate([$row]); |
|||||
328 | 8 | return reset($models) ?: null; |
|||||
329 | } |
||||||
330 | |||||||
331 | 2 | return null; |
|||||
332 | } |
||||||
333 | |||||||
334 | /** |
||||||
335 | * Creates a DB command that can be used to execute this query. |
||||||
336 | * @param Connection|null $db the DB connection used to create the DB command. |
||||||
337 | * If `null`, the DB connection returned by [[modelClass]] will be used. |
||||||
338 | * @return Command the created DB command instance. |
||||||
339 | */ |
||||||
340 | 16 | public function createCommand($db = null) |
|||||
341 | { |
||||||
342 | /** @var ActiveRecord $modelClass */ |
||||||
343 | 16 | $modelClass = $this->modelClass; |
|||||
344 | 16 | if ($db === null) { |
|||||
345 | 16 | $db = $modelClass::getDb(); |
|||||
346 | } |
||||||
347 | |||||||
348 | 16 | if ($this->sql === null) { |
|||||
349 | 16 | list($sql, $params) = $db->getQueryBuilder()->build($this); |
|||||
350 | } else { |
||||||
351 | $sql = $this->sql; |
||||||
352 | $params = $this->params; |
||||||
353 | } |
||||||
354 | |||||||
355 | 16 | $command = $db->createCommand($sql, $params); |
|||||
356 | 16 | $this->setCommandCache($command); |
|||||
357 | |||||||
358 | 16 | return $command; |
|||||
359 | } |
||||||
360 | |||||||
361 | /** |
||||||
362 | * {@inheritdoc} |
||||||
363 | */ |
||||||
364 | 1 | protected function queryScalar($selectExpression, $db) |
|||||
365 | { |
||||||
366 | /** @var ActiveRecord $modelClass */ |
||||||
367 | 1 | $modelClass = $this->modelClass; |
|||||
368 | 1 | if ($db === null) { |
|||||
369 | 1 | $db = $modelClass::getDb(); |
|||||
370 | } |
||||||
371 | |||||||
372 | 1 | if ($this->sql === null) { |
|||||
373 | 1 | return parent::queryScalar($selectExpression, $db); |
|||||
374 | } |
||||||
375 | |||||||
376 | $command = (new Query())->select([$selectExpression]) |
||||||
377 | ->from(['c' => "({$this->sql})"]) |
||||||
378 | ->params($this->params) |
||||||
379 | ->createCommand($db); |
||||||
380 | $this->setCommandCache($command); |
||||||
381 | |||||||
382 | return $command->queryScalar(); |
||||||
383 | } |
||||||
384 | |||||||
385 | /** |
||||||
386 | * Joins with the specified relations. |
||||||
387 | * |
||||||
388 | * This method allows you to reuse existing relation definitions to perform JOIN queries. |
||||||
389 | * Based on the definition of the specified relation(s), the method will append one or multiple |
||||||
390 | * JOIN statements to the current query. |
||||||
391 | * |
||||||
392 | * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations, |
||||||
393 | * which is equivalent to calling [[with()]] using the specified relations. |
||||||
394 | * |
||||||
395 | * Note that because a JOIN query will be performed, you are responsible to disambiguate column names. |
||||||
396 | * |
||||||
397 | * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement |
||||||
398 | * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations. |
||||||
399 | * |
||||||
400 | * @param string|array $with the relations to be joined. This can either be a string, representing a relation name or |
||||||
401 | * an array with the following semantics: |
||||||
402 | * |
||||||
403 | * - Each array element represents a single relation. |
||||||
404 | * - You may specify the relation name as the array key and provide an anonymous functions that |
||||||
405 | * can be used to modify the relation queries on-the-fly as the array value. |
||||||
406 | * - If a relation query does not need modification, you may use the relation name as the array value. |
||||||
407 | * |
||||||
408 | * The relation name may optionally contain an alias for the relation table (e.g. `books b`). |
||||||
409 | * |
||||||
410 | * Sub-relations can also be specified, see [[with()]] for the syntax. |
||||||
411 | * |
||||||
412 | * In the following you find some examples: |
||||||
413 | * |
||||||
414 | * ```php |
||||||
415 | * // find all orders that contain books, and eager loading "books" |
||||||
416 | * Order::find()->joinWith('books', true, 'INNER JOIN')->all(); |
||||||
417 | * // find all orders, eager loading "books", and sort the orders and books by the book names. |
||||||
418 | * Order::find()->joinWith([ |
||||||
419 | * 'books' => function (\yii\db\ActiveQuery $query) { |
||||||
420 | * $query->orderBy('item.name'); |
||||||
421 | * } |
||||||
422 | * ])->all(); |
||||||
423 | * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table |
||||||
424 | * Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all(); |
||||||
425 | * ``` |
||||||
426 | * |
||||||
427 | * The alias syntax is available since version 2.0.7. |
||||||
428 | * |
||||||
429 | * @param bool|array $eagerLoading whether to eager load the relations |
||||||
430 | * specified in `$with`. When this is a boolean, it applies to all |
||||||
431 | * relations specified in `$with`. Use an array to explicitly list which |
||||||
432 | * relations in `$with` need to be eagerly loaded. Note, that this does |
||||||
433 | * not mean, that the relations are populated from the query result. An |
||||||
434 | * extra query will still be performed to bring in the related data. |
||||||
435 | * Defaults to `true`. |
||||||
436 | * @param string|array $joinType the join type of the relations specified in `$with`. |
||||||
437 | * When this is a string, it applies to all relations specified in `$with`. Use an array |
||||||
438 | * in the format of `relationName => joinType` to specify different join types for different relations. |
||||||
439 | * @return $this the query object itself |
||||||
440 | */ |
||||||
441 | public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN') |
||||||
442 | { |
||||||
443 | $relations = []; |
||||||
444 | foreach ((array) $with as $name => $callback) { |
||||||
445 | if (is_int($name)) { |
||||||
446 | $name = $callback; |
||||||
447 | $callback = null; |
||||||
448 | } |
||||||
449 | |||||||
450 | if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) { |
||||||
451 | // relation is defined with an alias, adjust callback to apply alias |
||||||
452 | list(, $relation, $alias) = $matches; |
||||||
453 | $name = $relation; |
||||||
454 | $callback = function ($query) use ($callback, $alias) { |
||||||
455 | /** @var self $query */ |
||||||
456 | $query->alias($alias); |
||||||
457 | if ($callback !== null) { |
||||||
458 | call_user_func($callback, $query); |
||||||
459 | } |
||||||
460 | }; |
||||||
461 | } |
||||||
462 | |||||||
463 | if ($callback === null) { |
||||||
464 | $relations[] = $name; |
||||||
465 | } else { |
||||||
466 | $relations[$name] = $callback; |
||||||
467 | } |
||||||
468 | } |
||||||
469 | $this->joinWith[] = [$relations, $eagerLoading, $joinType]; |
||||||
470 | return $this; |
||||||
471 | } |
||||||
472 | |||||||
473 | private function buildJoinWith() |
||||||
474 | { |
||||||
475 | $join = $this->join; |
||||||
476 | $this->join = []; |
||||||
477 | |||||||
478 | /** @var ActiveRecordInterface $modelClass */ |
||||||
479 | $modelClass = $this->modelClass; |
||||||
480 | $model = $modelClass::instance(); |
||||||
481 | foreach ($this->joinWith as $config) { |
||||||
482 | list($with, $eagerLoading, $joinType) = $config; |
||||||
483 | $this->joinWithRelations($model, $with, $joinType); |
||||||
484 | |||||||
485 | if (is_array($eagerLoading)) { |
||||||
486 | foreach ($with as $name => $callback) { |
||||||
487 | if (is_int($name)) { |
||||||
488 | if (!in_array($callback, $eagerLoading, true)) { |
||||||
489 | unset($with[$name]); |
||||||
490 | } |
||||||
491 | } elseif (!in_array($name, $eagerLoading, true)) { |
||||||
492 | unset($with[$name]); |
||||||
493 | } |
||||||
494 | } |
||||||
495 | } elseif (!$eagerLoading) { |
||||||
496 | $with = []; |
||||||
497 | } |
||||||
498 | |||||||
499 | $this->with($with); |
||||||
500 | } |
||||||
501 | |||||||
502 | // remove duplicated joins added by joinWithRelations that may be added |
||||||
503 | // e.g. when joining a relation and a via relation at the same time |
||||||
504 | $uniqueJoins = []; |
||||||
505 | foreach ($this->join as $j) { |
||||||
506 | $uniqueJoins[serialize($j)] = $j; |
||||||
507 | } |
||||||
508 | $this->join = array_values($uniqueJoins); |
||||||
509 | |||||||
510 | // https://github.com/yiisoft/yii2/issues/16092 |
||||||
511 | $uniqueJoinsByTableName = []; |
||||||
512 | foreach ($this->join as $config) { |
||||||
513 | $tableName = serialize($config[1]); |
||||||
514 | if (!array_key_exists($tableName, $uniqueJoinsByTableName)) { |
||||||
515 | $uniqueJoinsByTableName[$tableName] = $config; |
||||||
516 | } |
||||||
517 | } |
||||||
518 | $this->join = array_values($uniqueJoinsByTableName); |
||||||
519 | |||||||
520 | if (!empty($join)) { |
||||||
521 | // append explicit join to joinWith() |
||||||
522 | // https://github.com/yiisoft/yii2/issues/2880 |
||||||
523 | $this->join = empty($this->join) ? $join : array_merge($this->join, $join); |
||||||
524 | } |
||||||
525 | } |
||||||
526 | |||||||
527 | /** |
||||||
528 | * Inner joins with the specified relations. |
||||||
529 | * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN". |
||||||
530 | * Please refer to [[joinWith()]] for detailed usage of this method. |
||||||
531 | * @param string|array $with the relations to be joined with. |
||||||
532 | * @param bool|array $eagerLoading whether to eager load the relations. |
||||||
533 | * Note, that this does not mean, that the relations are populated from the |
||||||
534 | * query result. An extra query will still be performed to bring in the |
||||||
535 | * related data. |
||||||
536 | * @return $this the query object itself |
||||||
537 | * @see joinWith() |
||||||
538 | */ |
||||||
539 | public function innerJoinWith($with, $eagerLoading = true) |
||||||
540 | { |
||||||
541 | return $this->joinWith($with, $eagerLoading, 'INNER JOIN'); |
||||||
542 | } |
||||||
543 | |||||||
544 | /** |
||||||
545 | * Modifies the current query by adding join fragments based on the given relations. |
||||||
546 | * @param ActiveRecord $model the primary model |
||||||
547 | * @param array $with the relations to be joined |
||||||
548 | * @param string|array $joinType the join type |
||||||
549 | */ |
||||||
550 | private function joinWithRelations($model, $with, $joinType) |
||||||
551 | { |
||||||
552 | $relations = []; |
||||||
553 | |||||||
554 | foreach ($with as $name => $callback) { |
||||||
555 | if (is_int($name)) { |
||||||
556 | $name = $callback; |
||||||
557 | $callback = null; |
||||||
558 | } |
||||||
559 | |||||||
560 | $primaryModel = $model; |
||||||
561 | $parent = $this; |
||||||
562 | $prefix = ''; |
||||||
563 | while (($pos = strpos($name, '.')) !== false) { |
||||||
564 | $childName = substr($name, $pos + 1); |
||||||
565 | $name = substr($name, 0, $pos); |
||||||
566 | $fullName = $prefix === '' ? $name : "$prefix.$name"; |
||||||
567 | if (!isset($relations[$fullName])) { |
||||||
568 | $relations[$fullName] = $relation = $primaryModel->getRelation($name); |
||||||
569 | $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName)); |
||||||
570 | } else { |
||||||
571 | $relation = $relations[$fullName]; |
||||||
572 | } |
||||||
573 | /** @var ActiveRecordInterface $relationModelClass */ |
||||||
574 | $relationModelClass = $relation->modelClass; |
||||||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||||||
575 | $primaryModel = $relationModelClass::instance(); |
||||||
576 | $parent = $relation; |
||||||
577 | $prefix = $fullName; |
||||||
578 | $name = $childName; |
||||||
579 | } |
||||||
580 | |||||||
581 | $fullName = $prefix === '' ? $name : "$prefix.$name"; |
||||||
582 | if (!isset($relations[$fullName])) { |
||||||
583 | $relations[$fullName] = $relation = $primaryModel->getRelation($name); |
||||||
584 | if ($callback !== null) { |
||||||
585 | call_user_func($callback, $relation); |
||||||
0 ignored issues
–
show
$callback of type null is incompatible with the type callable expected by parameter $callback of call_user_func() .
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
586 | } |
||||||
587 | if (!empty($relation->joinWith)) { |
||||||
0 ignored issues
–
show
|
|||||||
588 | $relation->buildJoinWith(); |
||||||
0 ignored issues
–
show
The method
buildJoinWith() does not exist on yii\db\ActiveQueryInterface . Since it exists in all sub-types, consider adding an abstract or default implementation to yii\db\ActiveQueryInterface .
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
589 | } |
||||||
590 | $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName)); |
||||||
591 | } |
||||||
592 | } |
||||||
593 | } |
||||||
594 | |||||||
595 | /** |
||||||
596 | * Returns the join type based on the given join type parameter and the relation name. |
||||||
597 | * @param string|array $joinType the given join type(s) |
||||||
598 | * @param string $name relation name |
||||||
599 | * @return string the real join type |
||||||
600 | */ |
||||||
601 | private function getJoinType($joinType, $name) |
||||||
602 | { |
||||||
603 | if (is_array($joinType) && isset($joinType[$name])) { |
||||||
604 | return $joinType[$name]; |
||||||
605 | } |
||||||
606 | |||||||
607 | return is_string($joinType) ? $joinType : 'INNER JOIN'; |
||||||
608 | } |
||||||
609 | |||||||
610 | /** |
||||||
611 | * Returns the table name and the table alias for [[modelClass]]. |
||||||
612 | * @return array the table name and the table alias. |
||||||
613 | * @since 2.0.16 |
||||||
614 | */ |
||||||
615 | protected function getTableNameAndAlias() |
||||||
616 | { |
||||||
617 | if (empty($this->from)) { |
||||||
618 | $tableName = $this->getPrimaryTableName(); |
||||||
619 | } else { |
||||||
620 | $tableName = ''; |
||||||
621 | // if the first entry in "from" is an alias-tablename-pair return it directly |
||||||
622 | foreach ($this->from as $alias => $tableName) { |
||||||
623 | if (is_string($alias)) { |
||||||
624 | return [$tableName, $alias]; |
||||||
625 | } |
||||||
626 | break; |
||||||
627 | } |
||||||
628 | } |
||||||
629 | |||||||
630 | if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) { |
||||||
631 | $alias = $matches[2]; |
||||||
632 | } else { |
||||||
633 | $alias = $tableName; |
||||||
634 | } |
||||||
635 | |||||||
636 | return [$tableName, $alias]; |
||||||
637 | } |
||||||
638 | |||||||
639 | /** |
||||||
640 | * Joins a parent query with a child query. |
||||||
641 | * The current query object will be modified accordingly. |
||||||
642 | * @param ActiveQuery $parent |
||||||
643 | * @param ActiveQuery $child |
||||||
644 | * @param string $joinType |
||||||
645 | */ |
||||||
646 | private function joinWithRelation($parent, $child, $joinType) |
||||||
647 | { |
||||||
648 | $via = $child->via; |
||||||
649 | $child->via = null; |
||||||
650 | if ($via instanceof self) { |
||||||
651 | // via table |
||||||
652 | $this->joinWithRelation($parent, $via, $joinType); |
||||||
653 | $this->joinWithRelation($via, $child, $joinType); |
||||||
654 | return; |
||||||
655 | } elseif (is_array($via)) { |
||||||
656 | // via relation |
||||||
657 | $this->joinWithRelation($parent, $via[1], $joinType); |
||||||
658 | $this->joinWithRelation($via[1], $child, $joinType); |
||||||
659 | return; |
||||||
660 | } |
||||||
661 | |||||||
662 | list($parentTable, $parentAlias) = $parent->getTableNameAndAlias(); |
||||||
663 | list($childTable, $childAlias) = $child->getTableNameAndAlias(); |
||||||
664 | |||||||
665 | if (!empty($child->link)) { |
||||||
666 | if (strpos($parentAlias, '{{') === false) { |
||||||
667 | $parentAlias = '{{' . $parentAlias . '}}'; |
||||||
668 | } |
||||||
669 | if (strpos($childAlias, '{{') === false) { |
||||||
670 | $childAlias = '{{' . $childAlias . '}}'; |
||||||
671 | } |
||||||
672 | |||||||
673 | $on = []; |
||||||
674 | foreach ($child->link as $childColumn => $parentColumn) { |
||||||
675 | $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]"; |
||||||
676 | } |
||||||
677 | $on = implode(' AND ', $on); |
||||||
678 | if (!empty($child->on)) { |
||||||
679 | $on = ['and', $on, $child->on]; |
||||||
680 | } |
||||||
681 | } else { |
||||||
682 | $on = $child->on; |
||||||
683 | } |
||||||
684 | $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on); |
||||||
685 | |||||||
686 | if (!empty($child->where)) { |
||||||
687 | $this->andWhere($child->where); |
||||||
688 | } |
||||||
689 | if (!empty($child->having)) { |
||||||
690 | $this->andHaving($child->having); |
||||||
691 | } |
||||||
692 | if (!empty($child->orderBy)) { |
||||||
693 | $this->addOrderBy($child->orderBy); |
||||||
694 | } |
||||||
695 | if (!empty($child->groupBy)) { |
||||||
696 | $this->addGroupBy($child->groupBy); |
||||||
697 | } |
||||||
698 | if (!empty($child->params)) { |
||||||
699 | $this->addParams($child->params); |
||||||
700 | } |
||||||
701 | if (!empty($child->join)) { |
||||||
702 | foreach ($child->join as $join) { |
||||||
703 | $this->join[] = $join; |
||||||
704 | } |
||||||
705 | } |
||||||
706 | if (!empty($child->union)) { |
||||||
707 | foreach ($child->union as $union) { |
||||||
708 | $this->union[] = $union; |
||||||
709 | } |
||||||
710 | } |
||||||
711 | } |
||||||
712 | |||||||
713 | /** |
||||||
714 | * Sets the ON condition for a relational query. |
||||||
715 | * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called. |
||||||
716 | * Otherwise, the condition will be used in the WHERE part of a query. |
||||||
717 | * |
||||||
718 | * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class: |
||||||
719 | * |
||||||
720 | * ```php |
||||||
721 | * public function getActiveUsers() |
||||||
722 | * { |
||||||
723 | * return $this->hasMany(User::class, ['id' => 'user_id']) |
||||||
724 | * ->onCondition(['active' => true]); |
||||||
725 | * } |
||||||
726 | * ``` |
||||||
727 | * |
||||||
728 | * Note that this condition is applied in case of a join as well as when fetching the related records. |
||||||
729 | * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary |
||||||
730 | * record will cause an error in a non-join-query. |
||||||
731 | * |
||||||
732 | * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter. |
||||||
733 | * @param array $params the parameters (name => value) to be bound to the query. |
||||||
734 | * @return $this the query object itself |
||||||
735 | */ |
||||||
736 | public function onCondition($condition, $params = []) |
||||||
737 | { |
||||||
738 | $this->on = $condition; |
||||||
739 | $this->addParams($params); |
||||||
740 | return $this; |
||||||
741 | } |
||||||
742 | |||||||
743 | /** |
||||||
744 | * Adds an additional ON condition to the existing one. |
||||||
745 | * The new condition and the existing one will be joined using the 'AND' operator. |
||||||
746 | * @param string|array $condition the new ON condition. Please refer to [[where()]] |
||||||
747 | * on how to specify this parameter. |
||||||
748 | * @param array $params the parameters (name => value) to be bound to the query. |
||||||
749 | * @return $this the query object itself |
||||||
750 | * @see onCondition() |
||||||
751 | * @see orOnCondition() |
||||||
752 | */ |
||||||
753 | public function andOnCondition($condition, $params = []) |
||||||
754 | { |
||||||
755 | if ($this->on === null) { |
||||||
756 | $this->on = $condition; |
||||||
757 | } else { |
||||||
758 | $this->on = ['and', $this->on, $condition]; |
||||||
759 | } |
||||||
760 | $this->addParams($params); |
||||||
761 | return $this; |
||||||
762 | } |
||||||
763 | |||||||
764 | /** |
||||||
765 | * Adds an additional ON condition to the existing one. |
||||||
766 | * The new condition and the existing one will be joined using the 'OR' operator. |
||||||
767 | * @param string|array $condition the new ON condition. Please refer to [[where()]] |
||||||
768 | * on how to specify this parameter. |
||||||
769 | * @param array $params the parameters (name => value) to be bound to the query. |
||||||
770 | * @return $this the query object itself |
||||||
771 | * @see onCondition() |
||||||
772 | * @see andOnCondition() |
||||||
773 | */ |
||||||
774 | public function orOnCondition($condition, $params = []) |
||||||
775 | { |
||||||
776 | if ($this->on === null) { |
||||||
777 | $this->on = $condition; |
||||||
778 | } else { |
||||||
779 | $this->on = ['or', $this->on, $condition]; |
||||||
780 | } |
||||||
781 | $this->addParams($params); |
||||||
782 | return $this; |
||||||
783 | } |
||||||
784 | |||||||
785 | /** |
||||||
786 | * Specifies the junction table for a relational query. |
||||||
787 | * |
||||||
788 | * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class: |
||||||
789 | * |
||||||
790 | * ```php |
||||||
791 | * public function getItems() |
||||||
792 | * { |
||||||
793 | * return $this->hasMany(Item::class, ['id' => 'item_id']) |
||||||
794 | * ->viaTable('order_item', ['order_id' => 'id']); |
||||||
795 | * } |
||||||
796 | * ``` |
||||||
797 | * |
||||||
798 | * @param string $tableName the name of the junction table. |
||||||
799 | * @param array $link the link between the junction table and the table associated with [[primaryModel]]. |
||||||
800 | * The keys of the array represent the columns in the junction table, and the values represent the columns |
||||||
801 | * in the [[primaryModel]] table. |
||||||
802 | * @param callable|null $callable a PHP callback for customizing the relation associated with the junction table. |
||||||
803 | * Its signature should be `function($query)`, where `$query` is the query to be customized. |
||||||
804 | * @return $this the query object itself |
||||||
805 | * @throws InvalidConfigException when query is not initialized properly |
||||||
806 | * @see via() |
||||||
807 | */ |
||||||
808 | public function viaTable($tableName, $link, ?callable $callable = null) |
||||||
809 | { |
||||||
810 | $modelClass = $this->primaryModel ? get_class($this->primaryModel) : $this->modelClass; |
||||||
811 | $relation = new self($modelClass, [ |
||||||
812 | 'from' => [$tableName], |
||||||
813 | 'link' => $link, |
||||||
814 | 'multiple' => true, |
||||||
815 | 'asArray' => true, |
||||||
816 | ]); |
||||||
817 | $this->via = $relation; |
||||||
818 | if ($callable !== null) { |
||||||
819 | call_user_func($callable, $relation); |
||||||
820 | } |
||||||
821 | |||||||
822 | return $this; |
||||||
823 | } |
||||||
824 | |||||||
825 | /** |
||||||
826 | * Define an alias for the table defined in [[modelClass]]. |
||||||
827 | * |
||||||
828 | * This method will adjust [[from]] so that an already defined alias will be overwritten. |
||||||
829 | * If none was defined, [[from]] will be populated with the given alias. |
||||||
830 | * |
||||||
831 | * @param string $alias the table alias. |
||||||
832 | * @return $this the query object itself |
||||||
833 | * @since 2.0.7 |
||||||
834 | */ |
||||||
835 | public function alias($alias) |
||||||
836 | { |
||||||
837 | if (empty($this->from) || count($this->from) < 2) { |
||||||
838 | list($tableName) = $this->getTableNameAndAlias(); |
||||||
839 | $this->from = [$alias => $tableName]; |
||||||
840 | } else { |
||||||
841 | $tableName = $this->getPrimaryTableName(); |
||||||
842 | |||||||
843 | foreach ($this->from as $key => $table) { |
||||||
844 | if ($table === $tableName) { |
||||||
845 | unset($this->from[$key]); |
||||||
846 | $this->from[$alias] = $tableName; |
||||||
847 | } |
||||||
848 | } |
||||||
849 | } |
||||||
850 | |||||||
851 | return $this; |
||||||
852 | } |
||||||
853 | |||||||
854 | /** |
||||||
855 | * {@inheritdoc} |
||||||
856 | * @since 2.0.12 |
||||||
857 | */ |
||||||
858 | 9 | public function getTablesUsedInFrom() |
|||||
859 | { |
||||||
860 | 9 | if (empty($this->from)) { |
|||||
861 | 9 | return $this->cleanUpTableNames([$this->getPrimaryTableName()]); |
|||||
862 | } |
||||||
863 | |||||||
864 | return parent::getTablesUsedInFrom(); |
||||||
865 | } |
||||||
866 | |||||||
867 | /** |
||||||
868 | * @return string primary table name |
||||||
869 | * @since 2.0.12 |
||||||
870 | */ |
||||||
871 | 12 | protected function getPrimaryTableName() |
|||||
872 | { |
||||||
873 | /** @var ActiveRecord $modelClass */ |
||||||
874 | 12 | $modelClass = $this->modelClass; |
|||||
875 | 12 | return $modelClass::tableName(); |
|||||
876 | } |
||||||
877 | } |
||||||
878 |