ActiveRelationTrait.php 21 KB

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