ActiveRelationTrait.php 23 KB

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