LinkableBehavior.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. /**
  4. * LinkableBehavior
  5. * Light-weight approach for data mining on deep relations between models.
  6. * Join tables based on model relations to easily enable right to left find operations.
  7. * Original behavior by rafaelbandeira3 on GitHub.
  8. * Includes modifications from Terr, n8man, and Chad Jablonski
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * GiulianoB ( https://github.com/giulianob/linkable )
  14. *
  15. * @version 1.0;
  16. *
  17. * @version 1.1:
  18. * -Brought in improvements and test cases from Terr. However, THIS VERSION OF LINKABLE IS NOT DROP IN COMPATIBLE WITH Terr's VERSION!
  19. * -If fields aren't specified, will now return all columns of that model
  20. * -No need to specify the foreign key condition if a custom condition is given. Linkable will automatically include the foreign key relationship.
  21. * -Ability to specify the exact condition Linkable should use (e.g. $this->Post->find('first', array('link' => array('User' => array('conditions' => array('exactly' => 'User.last_post_id = Post.id'))))) )
  22. * This is usually required when doing on-the-fly joins since Linkable generally assumes a belongsTo relationship when no specific relationship is found and may produce invalid foreign key conditions.
  23. * -Linkable will no longer break queries that use SQL COUNTs
  24. *
  25. * @version 1.2:
  26. * @modified Mark Scherer
  27. * - works with cakephp2.0 (89.84 test coverage)
  28. */
  29. class LinkableBehavior extends ModelBehavior {
  30. protected $_key = 'link';
  31. protected $_options = array(
  32. 'type' => true, 'table' => true, 'alias' => true,
  33. 'conditions' => true, 'fields' => true, 'reference' => true,
  34. 'class' => true, 'defaults' => true
  35. );
  36. protected $_defaults = array('type' => 'LEFT');
  37. public function beforeFind(Model $Model, $query) {
  38. if (isset($query[$this->_key])) {
  39. $optionsDefaults = $this->_defaults + array('reference' => $Model->alias, $this->_key => array());
  40. $optionsKeys = $this->_options + array($this->_key => true);
  41. // If containable is being used, then let it set the recursive!
  42. if (empty($query['contain'])) {
  43. $query = am(array('joins' => array()), $query, array('recursive' => -1));
  44. } else {
  45. $query = am(array('joins' => array()), $query);
  46. }
  47. $iterators[] = $query[$this->_key];
  48. $cont = 0;
  49. do {
  50. $iterator = $iterators[$cont];
  51. $defaults = $optionsDefaults;
  52. if (isset($iterator['defaults'])) {
  53. $defaults = array_merge($defaults, $iterator['defaults']);
  54. unset($iterator['defaults']);
  55. }
  56. $iterations = Set::normalize($iterator);
  57. foreach ($iterations as $alias => $options) {
  58. if (is_null($options)) {
  59. $options = array();
  60. }
  61. $options = am($defaults, compact('alias'), $options);
  62. if (empty($options['alias'])) {
  63. throw new InvalidArgumentException(sprintf('%s::%s must receive aliased links', get_class($this), __FUNCTION__));
  64. }
  65. if (empty($options['table']) && empty($options['class'])) {
  66. $options['class'] = $options['alias'];
  67. } elseif (!empty($options['table']) && empty($options['class'])) {
  68. $options['class'] = Inflector::classify($options['table']);
  69. }
  70. // the incoming model to be linked in query
  71. $_Model = ClassRegistry::init($options['class']);
  72. // the already in query model that links to $_Model
  73. $Reference = ClassRegistry::init($options['reference']);
  74. $db = $_Model->getDataSource();
  75. $associations = $_Model->getAssociated();
  76. if (isset($Reference->belongsTo[$_Model->alias])) {
  77. $type = 'hasOne';
  78. $association = $Reference->belongsTo[$_Model->alias];
  79. } elseif (isset($associations[$Reference->alias])) {
  80. $type = $associations[$Reference->alias];
  81. $association = $_Model->{$type}[$Reference->alias];
  82. } else {
  83. $_Model->bindModel(array('belongsTo' => array($Reference->alias)));
  84. $type = 'belongsTo';
  85. $association = $_Model->{$type}[$Reference->alias];
  86. $_Model->unbindModel(array('belongsTo' => array($Reference->alias)));
  87. }
  88. if (!isset($options['conditions'])) {
  89. $options['conditions'] = array();
  90. } elseif (!is_array($options['conditions'])) {
  91. // Support for string conditions
  92. $options['conditions'] = array($options['conditions']);
  93. }
  94. if (isset($options['conditions']['exactly'])) {
  95. if (is_array($options['conditions']['exactly']))
  96. $options['conditions'] = reset($options['conditions']['exactly']);
  97. else
  98. $options['conditions'] = array($options['conditions']['exactly']);
  99. } else {
  100. if ($type === 'belongsTo') {
  101. $modelKey = $_Model->escapeField($association['foreignKey']);
  102. $referenceKey = $Reference->escapeField($Reference->primaryKey);
  103. $options['conditions'][] = "{$referenceKey} = {$modelKey}";
  104. } elseif ($type === 'hasAndBelongsToMany') {
  105. if (isset($association['with'])) {
  106. $Link = $_Model->{$association['with']};
  107. if (isset($Link->belongsTo[$_Model->alias])) {
  108. $modelLink = $Link->escapeField($Link->belongsTo[$_Model->alias]['foreignKey']);
  109. }
  110. if (isset($Link->belongsTo[$Reference->alias])) {
  111. $referenceLink = $Link->escapeField($Link->belongsTo[$Reference->alias]['foreignKey']);
  112. }
  113. } else {
  114. $Link = $_Model->{Inflector::classify($association['joinTable'])};
  115. }
  116. if (empty($modelLink)) {
  117. $modelLink = $Link->escapeField(Inflector::underscore($_Model->alias) . '_id');
  118. }
  119. if (empty($referenceLink)) {
  120. $referenceLink = $Link->escapeField(Inflector::underscore($Reference->alias) . '_id');
  121. }
  122. $referenceKey = $Reference->escapeField();
  123. $query['joins'][] = array(
  124. 'alias' => $Link->alias,
  125. 'table' => $Link->table, //$Link->getDataSource()->fullTableName($Link),
  126. 'conditions' => "{$referenceLink} = {$referenceKey}",
  127. 'type' => 'LEFT'
  128. );
  129. $modelKey = $_Model->escapeField();
  130. $options['conditions'][] = "{$modelLink} = {$modelKey}";
  131. } else {
  132. $referenceKey = $Reference->escapeField($association['foreignKey']);
  133. $modelKey = $_Model->escapeField($_Model->primaryKey);
  134. $options['conditions'][] = "{$modelKey} = {$referenceKey}";
  135. }
  136. }
  137. if (empty($options['table'])) {
  138. $options['table'] = $_Model->table;
  139. }
  140. // Decide whether we should mess with the fields or not
  141. // If this query is a COUNT query then we just leave it alone
  142. if (!isset($query['fields']) || is_array($query['fields']) || strpos($query['fields'], 'COUNT(*)') === FALSE) {
  143. if (!empty($options['fields'])) {
  144. if ($options['fields'] === true && !empty($association['fields'])) {
  145. $options['fields'] = $db->fields($_Model, null, $association['fields']);
  146. } elseif ($options['fields'] === true) {
  147. $options['fields'] = $db->fields($_Model);
  148. } else {
  149. $options['fields'] = $db->fields($_Model, null, $options['fields']);
  150. }
  151. } elseif (!isset($options['fields']) || (isset($options['fields']) && !is_array($options['fields']))) {
  152. if (!empty($association['fields'])) {
  153. $options['fields'] = $db->fields($_Model, null, $association['fields']);
  154. } else {
  155. $options['fields'] = $db->fields($_Model);
  156. }
  157. }
  158. if (!empty($options['class']) && $options['class'] !== $alias) {
  159. $options['fields'] = str_replace($options['class'], $alias, $options['fields']);
  160. }
  161. if (is_array($query['fields'])) {
  162. $query['fields'] = array_merge($query['fields'], $options['fields']);
  163. } else {
  164. // If user didn't specify any fields then select all fields by default (just as find would)
  165. $query['fields'] = array_merge($db->fields($Model), $options['fields']);
  166. }
  167. }
  168. $options[$this->_key] = am($options[$this->_key], array_diff_key($options, $optionsKeys));
  169. $options = array_intersect_key($options, $optionsKeys);
  170. if (!empty($options[$this->_key])) {
  171. $iterators[] = $options[$this->_key] + array('defaults' => array_merge($defaults, array('reference' => $options['class'])));
  172. }
  173. $query['joins'][] = array_intersect_key($options, array('type' => true, 'alias' => true, 'table' => true, 'conditions' => true));
  174. }
  175. $cont++;
  176. $notDone = isset($iterators[$cont]);
  177. } while ($notDone);
  178. }
  179. unset($query['link']);
  180. return $query;
  181. }
  182. }