ActiveRelationTrait.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. namespace yii\db;
  8. use yii\base\InvalidArgumentException;
  9. use yii\base\InvalidConfigException;
  10. /**
  11. * ActiveRelationTrait implements the common methods and properties for active record relational queries.
  12. *
  13. * @author Qiang Xue <qiang.xue@gmail.com>
  14. * @author Carsten Brandt <mail@cebe.cc>
  15. * @since 2.0
  16. * @phpcs:disable Squiz.NamingConventions.ValidVariableName.PrivateNoUnderscore
  17. *
  18. * @method ActiveRecordInterface|array|null one($db = null) See [[ActiveQueryInterface::one()]] for more info.
  19. * @method ActiveRecordInterface[] all($db = null) See [[ActiveQueryInterface::all()]] for more info.
  20. * @property ActiveRecord $modelClass
  21. */
  22. trait ActiveRelationTrait
  23. {
  24. /**
  25. * @var bool whether this query represents a relation to more than one record.
  26. * This property is only used in relational context. If true, this relation will
  27. * populate all query results into AR instances using [[Query::all()|all()]].
  28. * If false, only the first row of the results will be retrieved using [[Query::one()|one()]].
  29. */
  30. public $multiple;
  31. /**
  32. * @var ActiveRecord the primary model of a relational query.
  33. * This is used only in lazy loading with dynamic query options.
  34. */
  35. public $primaryModel;
  36. /**
  37. * @var array the columns of the primary and foreign tables that establish a relation.
  38. * The array keys must be columns of the table for this relation, and the array values
  39. * must be the corresponding columns from the primary table.
  40. * Do not prefix or quote the column names as this will be done automatically by Yii.
  41. * This property is only used in relational context.
  42. */
  43. public $link;
  44. /**
  45. * @var array|object the query associated with the junction table. Please call [[via()]]
  46. * to set this property instead of directly setting it.
  47. * This property is only used in relational context.
  48. * @see via()
  49. */
  50. public $via;
  51. /**
  52. * @var string the name of the relation that is the inverse of this relation.
  53. * For example, an order has a customer, which means the inverse of the "customer" relation
  54. * is the "orders", and the inverse of the "orders" relation is the "customer".
  55. * If this property is set, the primary record(s) will be referenced through the specified relation.
  56. * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
  57. * and accessing the customer of an order will not trigger new DB query.
  58. * This property is only used in relational context.
  59. * @see inverseOf()
  60. */
  61. public $inverseOf;
  62. private $viaMap;
  63. /**
  64. * Clones internal objects.
  65. */
  66. public function __clone()
  67. {
  68. parent::__clone();
  69. // make a clone of "via" object so that the same query object can be reused multiple times
  70. if (is_object($this->via)) {
  71. $this->via = clone $this->via;
  72. } elseif (is_array($this->via)) {
  73. $this->via = [$this->via[0], clone $this->via[1], $this->via[2]];
  74. }
  75. }
  76. /**
  77. * Specifies the relation associated with the junction table.
  78. *
  79. * Use this method to specify a pivot record/table when declaring a relation in the [[ActiveRecord]] class:
  80. *
  81. * ```php
  82. * class Order extends ActiveRecord
  83. * {
  84. * public function getOrderItems() {
  85. * return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
  86. * }
  87. *
  88. * public function getItems() {
  89. * return $this->hasMany(Item::class, ['id' => 'item_id'])
  90. * ->via('orderItems');
  91. * }
  92. * }
  93. * ```
  94. *
  95. * @param string $relationName the relation name. This refers to a relation declared in [[primaryModel]].
  96. * @param callable|null $callable a PHP callback for customizing the relation associated with the junction table.
  97. * Its signature should be `function($query)`, where `$query` is the query to be customized.
  98. * @return $this the relation object itself.
  99. */
  100. public function via($relationName, ?callable $callable = null)
  101. {
  102. $relation = $this->primaryModel->getRelation($relationName);
  103. $callableUsed = $callable !== null;
  104. $this->via = [$relationName, $relation, $callableUsed];
  105. if ($callable !== null) {
  106. call_user_func($callable, $relation);
  107. }
  108. return $this;
  109. }
  110. /**
  111. * Sets the name of the relation that is the inverse of this relation.
  112. * For example, a customer has orders, which means the inverse of the "orders" relation is the "customer".
  113. * If this property is set, the primary record(s) will be referenced through the specified relation.
  114. * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
  115. * and accessing the customer of an order will not trigger a new DB query.
  116. *
  117. * Use this method when declaring a relation in the [[ActiveRecord]] class, e.g. in Customer model:
  118. *
  119. * ```php
  120. * public function getOrders()
  121. * {
  122. * return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer');
  123. * }
  124. * ```
  125. *
  126. * This also may be used for Order model, but with caution:
  127. *
  128. * ```php
  129. * public function getCustomer()
  130. * {
  131. * return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders');
  132. * }
  133. * ```
  134. *
  135. * in this case result will depend on how order(s) was loaded.
  136. * Let's suppose customer has several orders. If only one order was loaded:
  137. *
  138. * ```php
  139. * $orders = Order::find()->where(['id' => 1])->all();
  140. * $customerOrders = $orders[0]->customer->orders;
  141. * ```
  142. *
  143. * variable `$customerOrders` will contain only one order. If orders was loaded like this:
  144. *
  145. * ```php
  146. * $orders = Order::find()->with('customer')->where(['customer_id' => 1])->all();
  147. * $customerOrders = $orders[0]->customer->orders;
  148. * ```
  149. *
  150. * variable `$customerOrders` will contain all orders of the customer.
  151. *
  152. * @param string $relationName the name of the relation that is the inverse of this relation.
  153. * @return $this the relation object itself.
  154. */
  155. public function inverseOf($relationName)
  156. {
  157. $this->inverseOf = $relationName;
  158. return $this;
  159. }
  160. /**
  161. * Finds the related records for the specified primary record.
  162. * This method is invoked when a relation of an ActiveRecord is being accessed lazily.
  163. * @param string $name the relation name
  164. * @param ActiveRecordInterface|BaseActiveRecord $model the primary model
  165. * @return mixed the related record(s)
  166. * @throws InvalidArgumentException if the relation is invalid
  167. */
  168. public function findFor($name, $model)
  169. {
  170. if (method_exists($model, 'get' . $name)) {
  171. $method = new \ReflectionMethod($model, 'get' . $name);
  172. $realName = lcfirst(substr($method->getName(), 3));
  173. if ($realName !== $name) {
  174. throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($model) . " has a relation named \"$realName\" instead of \"$name\".");
  175. }
  176. }
  177. return $this->multiple ? $this->all() : $this->one();
  178. }
  179. /**
  180. * If applicable, populate the query's primary model into the related records' inverse relationship.
  181. * @param array $result the array of related records as generated by [[populate()]]
  182. * @since 2.0.9
  183. */
  184. private function addInverseRelations(&$result)
  185. {
  186. if ($this->inverseOf === null) {
  187. return;
  188. }
  189. foreach ($result as $i => $relatedModel) {
  190. if ($relatedModel instanceof ActiveRecordInterface) {
  191. if (!isset($inverseRelation)) {
  192. $inverseRelation = $relatedModel->getRelation($this->inverseOf);
  193. }
  194. $relatedModel->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel);
  195. } else {
  196. if (!isset($inverseRelation)) {
  197. /* @var $modelClass ActiveRecordInterface */
  198. $modelClass = $this->modelClass;
  199. $inverseRelation = $modelClass::instance()->getRelation($this->inverseOf);
  200. }
  201. $result[$i][$this->inverseOf] = $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel;
  202. }
  203. }
  204. }
  205. /**
  206. * Finds the related records and populates them into the primary models.
  207. * @param string $name the relation name
  208. * @param array $primaryModels primary models
  209. * @return array the related models
  210. * @throws InvalidConfigException if [[link]] is invalid
  211. */
  212. public function populateRelation($name, &$primaryModels)
  213. {
  214. if (!is_array($this->link)) {
  215. throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.');
  216. }
  217. if ($this->via instanceof self) {
  218. // via junction table
  219. /* @var $viaQuery ActiveRelationTrait */
  220. $viaQuery = $this->via;
  221. $viaModels = $viaQuery->findJunctionRows($primaryModels);
  222. $this->filterByModels($viaModels);
  223. } elseif (is_array($this->via)) {
  224. // via relation
  225. /* @var $viaQuery ActiveRelationTrait|ActiveQueryTrait */
  226. list($viaName, $viaQuery) = $this->via;
  227. if ($viaQuery->asArray === null) {
  228. // inherit asArray from primary query
  229. $viaQuery->asArray($this->asArray);
  230. }
  231. $viaQuery->primaryModel = null;
  232. $viaModels = array_filter($viaQuery->populateRelation($viaName, $primaryModels));
  233. $this->filterByModels($viaModels);
  234. } else {
  235. $this->filterByModels($primaryModels);
  236. }
  237. if (!$this->multiple && count($primaryModels) === 1) {
  238. $model = $this->one();
  239. $primaryModel = reset($primaryModels);
  240. if ($primaryModel instanceof ActiveRecordInterface) {
  241. $primaryModel->populateRelation($name, $model);
  242. } else {
  243. $primaryModels[key($primaryModels)][$name] = $model;
  244. }
  245. if ($this->inverseOf !== null) {
  246. $this->populateInverseRelation($primaryModels, [$model], $name, $this->inverseOf);
  247. }
  248. return [$model];
  249. }
  250. // https://github.com/yiisoft/yii2/issues/3197
  251. // delay indexing related models after buckets are built
  252. $indexBy = $this->indexBy;
  253. $this->indexBy = null;
  254. $models = $this->all();
  255. if (isset($viaModels, $viaQuery)) {
  256. $buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery);
  257. } else {
  258. $buckets = $this->buildBuckets($models, $this->link);
  259. }
  260. $this->indexBy = $indexBy;
  261. if ($this->indexBy !== null && $this->multiple) {
  262. $buckets = $this->indexBuckets($buckets, $this->indexBy);
  263. }
  264. $link = array_values($this->link);
  265. if (isset($viaQuery)) {
  266. $deepViaQuery = $viaQuery;
  267. while ($deepViaQuery->via) {
  268. $deepViaQuery = is_array($deepViaQuery->via) ? $deepViaQuery->via[1] : $deepViaQuery->via;
  269. };
  270. $link = array_values($deepViaQuery->link);
  271. }
  272. foreach ($primaryModels as $i => $primaryModel) {
  273. $keys = null;
  274. if ($this->multiple && count($link) === 1) {
  275. $primaryModelKey = reset($link);
  276. $keys = isset($primaryModel[$primaryModelKey]) ? $primaryModel[$primaryModelKey] : null;
  277. }
  278. if (is_array($keys)) {
  279. $value = [];
  280. foreach ($keys as $key) {
  281. $key = $this->normalizeModelKey($key);
  282. if (isset($buckets[$key])) {
  283. if ($this->indexBy !== null) {
  284. // if indexBy is set, array_merge will cause renumbering of numeric array
  285. foreach ($buckets[$key] as $bucketKey => $bucketValue) {
  286. $value[$bucketKey] = $bucketValue;
  287. }
  288. } else {
  289. $value = array_merge($value, $buckets[$key]);
  290. }
  291. }
  292. }
  293. } else {
  294. $key = $this->getModelKey($primaryModel, $link);
  295. $value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null);
  296. }
  297. if ($primaryModel instanceof ActiveRecordInterface) {
  298. $primaryModel->populateRelation($name, $value);
  299. } else {
  300. $primaryModels[$i][$name] = $value;
  301. }
  302. }
  303. if ($this->inverseOf !== null) {
  304. $this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf);
  305. }
  306. return $models;
  307. }
  308. /**
  309. * @param ActiveRecordInterface[] $primaryModels primary models
  310. * @param ActiveRecordInterface[] $models models
  311. * @param string $primaryName the primary relation name
  312. * @param string $name the relation name
  313. */
  314. private function populateInverseRelation(&$primaryModels, $models, $primaryName, $name)
  315. {
  316. if (empty($models) || empty($primaryModels)) {
  317. return;
  318. }
  319. $model = reset($models);
  320. /* @var $relation ActiveQueryInterface|ActiveQuery */
  321. if ($model instanceof ActiveRecordInterface) {
  322. $relation = $model->getRelation($name);
  323. } else {
  324. /* @var $modelClass ActiveRecordInterface */
  325. $modelClass = $this->modelClass;
  326. $relation = $modelClass::instance()->getRelation($name);
  327. }
  328. if ($relation->multiple) {
  329. $buckets = $this->buildBuckets($primaryModels, $relation->link, null, null, false);
  330. if ($model instanceof ActiveRecordInterface) {
  331. foreach ($models as $model) {
  332. $key = $this->getModelKey($model, $relation->link);
  333. $model->populateRelation($name, isset($buckets[$key]) ? $buckets[$key] : []);
  334. }
  335. } else {
  336. foreach ($primaryModels as $i => $primaryModel) {
  337. if ($this->multiple) {
  338. foreach ($primaryModel as $j => $m) {
  339. $key = $this->getModelKey($m, $relation->link);
  340. $primaryModels[$i][$j][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
  341. }
  342. } elseif (!empty($primaryModel[$primaryName])) {
  343. $key = $this->getModelKey($primaryModel[$primaryName], $relation->link);
  344. $primaryModels[$i][$primaryName][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
  345. }
  346. }
  347. }
  348. } elseif ($this->multiple) {
  349. foreach ($primaryModels as $i => $primaryModel) {
  350. foreach ($primaryModel[$primaryName] as $j => $m) {
  351. if ($m instanceof ActiveRecordInterface) {
  352. $m->populateRelation($name, $primaryModel);
  353. } else {
  354. $primaryModels[$i][$primaryName][$j][$name] = $primaryModel;
  355. }
  356. }
  357. }
  358. } else {
  359. foreach ($primaryModels as $i => $primaryModel) {
  360. if ($primaryModels[$i][$primaryName] instanceof ActiveRecordInterface) {
  361. $primaryModels[$i][$primaryName]->populateRelation($name, $primaryModel);
  362. } elseif (!empty($primaryModels[$i][$primaryName])) {
  363. $primaryModels[$i][$primaryName][$name] = $primaryModel;
  364. }
  365. }
  366. }
  367. }
  368. /**
  369. * @param array $models
  370. * @param array $link
  371. * @param array|null $viaModels
  372. * @param self|null $viaQuery
  373. * @param bool $checkMultiple
  374. * @return array
  375. */
  376. private function buildBuckets($models, $link, $viaModels = null, $viaQuery = null, $checkMultiple = true)
  377. {
  378. if ($viaModels !== null) {
  379. $map = [];
  380. $viaLink = $viaQuery->link;
  381. $viaLinkKeys = array_keys($viaLink);
  382. $linkValues = array_values($link);
  383. foreach ($viaModels as $viaModel) {
  384. $key1 = $this->getModelKey($viaModel, $viaLinkKeys);
  385. $key2 = $this->getModelKey($viaModel, $linkValues);
  386. $map[$key2][$key1] = true;
  387. }
  388. $viaQuery->viaMap = $map;
  389. $viaVia = $viaQuery->via;
  390. while ($viaVia) {
  391. $viaViaQuery = is_array($viaVia) ? $viaVia[1] : $viaVia;
  392. $map = $this->mapVia($map, $viaViaQuery->viaMap);
  393. $viaVia = $viaViaQuery->via;
  394. };
  395. }
  396. $buckets = [];
  397. $linkKeys = array_keys($link);
  398. if (isset($map)) {
  399. foreach ($models as $model) {
  400. $key = $this->getModelKey($model, $linkKeys);
  401. if (isset($map[$key])) {
  402. foreach (array_keys($map[$key]) as $key2) {
  403. $buckets[$key2][] = $model;
  404. }
  405. }
  406. }
  407. } else {
  408. foreach ($models as $model) {
  409. $key = $this->getModelKey($model, $linkKeys);
  410. $buckets[$key][] = $model;
  411. }
  412. }
  413. if ($checkMultiple && !$this->multiple) {
  414. foreach ($buckets as $i => $bucket) {
  415. $buckets[$i] = reset($bucket);
  416. }
  417. }
  418. return $buckets;
  419. }
  420. /**
  421. * @param array $map
  422. * @param array $viaMap
  423. * @return array
  424. */
  425. private function mapVia($map, $viaMap)
  426. {
  427. $resultMap = [];
  428. foreach ($map as $key => $linkKeys) {
  429. $resultMap[$key] = [];
  430. foreach (array_keys($linkKeys) as $linkKey) {
  431. $resultMap[$key] += $viaMap[$linkKey];
  432. }
  433. }
  434. return $resultMap;
  435. }
  436. /**
  437. * Indexes buckets by column name.
  438. *
  439. * @param array $buckets
  440. * @param string|callable $indexBy the name of the column by which the query results should be indexed by.
  441. * This can also be a callable (e.g. anonymous function) that returns the index value based on the given row data.
  442. * @return array
  443. */
  444. private function indexBuckets($buckets, $indexBy)
  445. {
  446. $result = [];
  447. foreach ($buckets as $key => $models) {
  448. $result[$key] = [];
  449. foreach ($models as $model) {
  450. $index = is_string($indexBy) ? $model[$indexBy] : call_user_func($indexBy, $model);
  451. $result[$key][$index] = $model;
  452. }
  453. }
  454. return $result;
  455. }
  456. /**
  457. * @param array $attributes the attributes to prefix
  458. * @return array
  459. */
  460. private function prefixKeyColumns($attributes)
  461. {
  462. if ($this instanceof ActiveQuery && (!empty($this->join) || !empty($this->joinWith))) {
  463. if (empty($this->from)) {
  464. /* @var $modelClass ActiveRecord */
  465. $modelClass = $this->modelClass;
  466. $alias = $modelClass::tableName();
  467. } else {
  468. foreach ($this->from as $alias => $table) {
  469. if (!is_string($alias)) {
  470. $alias = $table;
  471. }
  472. break;
  473. }
  474. }
  475. if (isset($alias)) {
  476. foreach ($attributes as $i => $attribute) {
  477. $attributes[$i] = "$alias.$attribute";
  478. }
  479. }
  480. }
  481. return $attributes;
  482. }
  483. /**
  484. * @param array $models
  485. */
  486. private function filterByModels($models)
  487. {
  488. $attributes = array_keys($this->link);
  489. $attributes = $this->prefixKeyColumns($attributes);
  490. $values = [];
  491. if (count($attributes) === 1) {
  492. // single key
  493. $attribute = reset($this->link);
  494. foreach ($models as $model) {
  495. $value = isset($model[$attribute]) || (is_object($model) && property_exists($model, $attribute)) ? $model[$attribute] : null;
  496. if ($value !== null) {
  497. if (is_array($value)) {
  498. $values = array_merge($values, $value);
  499. } elseif ($value instanceof ArrayExpression && $value->getDimension() === 1) {
  500. $values = array_merge($values, $value->getValue());
  501. } else {
  502. $values[] = $value;
  503. }
  504. }
  505. }
  506. if (empty($values)) {
  507. $this->emulateExecution();
  508. }
  509. } else {
  510. // composite keys
  511. // ensure keys of $this->link are prefixed the same way as $attributes
  512. $prefixedLink = array_combine($attributes, $this->link);
  513. foreach ($models as $model) {
  514. $v = [];
  515. foreach ($prefixedLink as $attribute => $link) {
  516. $v[$attribute] = $model[$link];
  517. }
  518. $values[] = $v;
  519. if (empty($v)) {
  520. $this->emulateExecution();
  521. }
  522. }
  523. }
  524. if (!empty($values)) {
  525. $scalarValues = [];
  526. $nonScalarValues = [];
  527. foreach ($values as $value) {
  528. if (is_scalar($value)) {
  529. $scalarValues[] = $value;
  530. } else {
  531. $nonScalarValues[] = $value;
  532. }
  533. }
  534. $scalarValues = array_unique($scalarValues);
  535. $values = array_merge($scalarValues, $nonScalarValues);
  536. }
  537. $this->andWhere(['in', $attributes, $values]);
  538. }
  539. /**
  540. * @param ActiveRecordInterface|array $model
  541. * @param array $attributes
  542. * @return string|false
  543. */
  544. private function getModelKey($model, $attributes)
  545. {
  546. $key = [];
  547. foreach ($attributes as $attribute) {
  548. if (isset($model[$attribute]) || (is_object($model) && property_exists($model, $attribute))) {
  549. $key[] = $this->normalizeModelKey($model[$attribute]);
  550. }
  551. }
  552. if (count($key) > 1) {
  553. return serialize($key);
  554. }
  555. return reset($key);
  556. }
  557. /**
  558. * @param mixed $value raw key value. Since 2.0.40 non-string values must be convertible to string (like special
  559. * objects for cross-DBMS relations, for example: `|MongoId`).
  560. * @return string normalized key value.
  561. */
  562. private function normalizeModelKey($value)
  563. {
  564. try {
  565. return (string)$value;
  566. } catch (\Exception $e) {
  567. throw new InvalidConfigException('Value must be convertable to string.');
  568. } catch (\Throwable $e) {
  569. throw new InvalidConfigException('Value must be convertable to string.');
  570. }
  571. }
  572. /**
  573. * @param array $primaryModels either array of AR instances or arrays
  574. * @return array
  575. */
  576. private function findJunctionRows($primaryModels)
  577. {
  578. if (empty($primaryModels)) {
  579. return [];
  580. }
  581. $this->filterByModels($primaryModels);
  582. /* @var $primaryModel ActiveRecord */
  583. $primaryModel = reset($primaryModels);
  584. if (!$primaryModel instanceof ActiveRecordInterface) {
  585. // when primaryModels are array of arrays (asArray case)
  586. $primaryModel = $this->modelClass;
  587. }
  588. return $this->asArray()->all($primaryModel::getDb());
  589. }
  590. }