HasManyThrough.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\model\relation;
  12. use Closure;
  13. use think\db\Query;
  14. use think\Loader;
  15. use think\Model;
  16. use think\model\Relation;
  17. class HasManyThrough extends Relation
  18. {
  19. // 中间关联表外键
  20. protected $throughKey;
  21. // 中间表模型
  22. protected $through;
  23. /**
  24. * 中间主键
  25. * @var string
  26. */
  27. protected $throughPk;
  28. /**
  29. * 架构函数
  30. * @access public
  31. * @param Model $parent 上级模型对象
  32. * @param string $model 模型名
  33. * @param string $through 中间模型名
  34. * @param string $foreignKey 关联外键
  35. * @param string $throughKey 关联外键
  36. * @param string $localKey 当前主键
  37. */
  38. public function __construct(Model $parent, $model, $through, $foreignKey, $throughKey, $localKey)
  39. {
  40. $this->parent = $parent;
  41. $this->model = $model;
  42. $this->through = (new $through)->db();
  43. $this->foreignKey = $foreignKey;
  44. $this->throughKey = $throughKey;
  45. $this->throughPk = $this->through->getPk();
  46. $this->localKey = $localKey;
  47. $this->query = (new $model)->db();
  48. }
  49. /**
  50. * 延迟获取关联数据
  51. * @access public
  52. * @param string $subRelation 子关联名
  53. * @param \Closure $closure 闭包查询条件
  54. * @return \think\Collection
  55. */
  56. public function getRelation($subRelation = '', $closure = null)
  57. {
  58. if ($closure instanceof Closure) {
  59. $closure($this->query);
  60. }
  61. $this->baseQuery();
  62. return $this->query->relation($subRelation)->select();
  63. }
  64. /**
  65. * 根据关联条件查询当前模型
  66. * @access public
  67. * @param string $operator 比较操作符
  68. * @param integer $count 个数
  69. * @param string $id 关联表的统计字段
  70. * @param string $joinType JOIN类型
  71. * @return Query
  72. */
  73. public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
  74. {
  75. $model = Loader::parseName(basename(str_replace('\\', '/', get_class($this->parent))));
  76. $throughTable = $this->through->getTable();
  77. $pk = $this->throughPk;
  78. $throughKey = $this->throughKey;
  79. $relation = (new $this->model)->db();
  80. $relationTable = $relation->getTable();
  81. $softDelete = $this->query->getOptions('soft_delete');
  82. if ('*' != $id) {
  83. $id = $relationTable . '.' . $relation->getPk();
  84. }
  85. return $this->parent->db()
  86. ->alias($model)
  87. ->field($model . '.*')
  88. ->join($throughTable, $throughTable . '.' . $this->foreignKey . '=' . $model . '.' . $this->localKey)
  89. ->join($relationTable, $relationTable . '.' . $throughKey . '=' . $throughTable . '.' . $this->throughPk)
  90. ->when($softDelete, function ($query) use ($softDelete, $relationTable) {
  91. $query->where($relationTable . strstr($softDelete[0], '.'), '=' == $softDelete[1][0] ? $softDelete[1][1] : null);
  92. })
  93. ->group($relationTable . '.' . $this->throughKey)
  94. ->having('count(' . $id . ')' . $operator . $count);
  95. }
  96. /**
  97. * 根据关联条件查询当前模型
  98. * @access public
  99. * @param mixed $where 查询条件(数组或者闭包)
  100. * @param mixed $fields 字段
  101. * @return Query
  102. */
  103. public function hasWhere($where = [], $fields = null)
  104. {
  105. $model = Loader::parseName(basename(str_replace('\\', '/', get_class($this->parent))));
  106. $throughTable = $this->through->getTable();
  107. $pk = $this->throughPk;
  108. $throughKey = $this->throughKey;
  109. $modelTable = (new $this->model)->db()->getTable();
  110. if (is_array($where)) {
  111. $this->getQueryWhere($where, $modelTable);
  112. }
  113. $fields = $this->getRelationQueryFields($fields, $model);
  114. $softDelete = $this->query->getOptions('soft_delete');
  115. return $this->parent->db()
  116. ->alias($model)
  117. ->join($throughTable, $throughTable . '.' . $this->foreignKey . '=' . $model . '.' . $this->localKey)
  118. ->join($modelTable, $modelTable . '.' . $throughKey . '=' . $throughTable . '.' . $this->throughPk)
  119. ->when($softDelete, function ($query) use ($softDelete, $modelTable) {
  120. $query->where($modelTable . strstr($softDelete[0], '.'), '=' == $softDelete[1][0] ? $softDelete[1][1] : null);
  121. })
  122. ->group($modelTable . '.' . $this->throughKey)
  123. ->where($where)
  124. ->field($fields);
  125. }
  126. /**
  127. * 预载入关联查询(数据集)
  128. * @access protected
  129. * @param array $resultSet 数据集
  130. * @param string $relation 当前关联名
  131. * @param mixed $subRelation 子关联名
  132. * @param Closure $closure 闭包
  133. * @return void
  134. */
  135. public function eagerlyResultSet(array &$resultSet, $relation, $subRelation = '', $closure = null)
  136. {
  137. $localKey = $this->localKey;
  138. $foreignKey = $this->foreignKey;
  139. $range = [];
  140. foreach ($resultSet as $result) {
  141. // 获取关联外键列表
  142. if (isset($result->$localKey)) {
  143. $range[] = $result->$localKey;
  144. }
  145. }
  146. if (!empty($range)) {
  147. $this->query->removeWhereField($foreignKey);
  148. $data = $this->eagerlyWhere([
  149. [$this->foreignKey, 'in', $range],
  150. ], $foreignKey, $relation, $subRelation, $closure);
  151. // 关联属性名
  152. $attr = Loader::parseName($relation);
  153. // 关联数据封装
  154. foreach ($resultSet as $result) {
  155. $pk = $result->$localKey;
  156. if (!isset($data[$pk])) {
  157. $data[$pk] = [];
  158. }
  159. foreach ($data[$pk] as &$relationModel) {
  160. $relationModel->setParent(clone $result);
  161. }
  162. // 设置关联属性
  163. $result->setRelation($attr, $this->resultSetBuild($data[$pk]));
  164. }
  165. }
  166. }
  167. /**
  168. * 预载入关联查询(数据)
  169. * @access protected
  170. * @param Model $result 数据对象
  171. * @param string $relation 当前关联名
  172. * @param mixed $subRelation 子关联名
  173. * @param Closure $closure 闭包
  174. * @return void
  175. */
  176. public function eagerlyResult($result, $relation, $subRelation = '', $closure = null)
  177. {
  178. $localKey = $this->localKey;
  179. $foreignKey = $this->foreignKey;
  180. $pk = $result->$localKey;
  181. $this->query->removeWhereField($foreignKey);
  182. $data = $this->eagerlyWhere([
  183. [$foreignKey, '=', $pk],
  184. ], $foreignKey, $relation, $subRelation, $closure);
  185. // 关联数据封装
  186. if (!isset($data[$pk])) {
  187. $data[$pk] = [];
  188. }
  189. foreach ($data[$pk] as &$relationModel) {
  190. $relationModel->setParent(clone $result);
  191. }
  192. $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$pk]));
  193. }
  194. /**
  195. * 关联模型预查询
  196. * @access public
  197. * @param array $where 关联预查询条件
  198. * @param string $key 关联键名
  199. * @param string $relation 关联名
  200. * @param mixed $subRelation 子关联
  201. * @param Closure $closure
  202. * @return array
  203. */
  204. protected function eagerlyWhere(array $where, $key, $relation, $subRelation = '', $closure = null)
  205. {
  206. // 预载入关联查询 支持嵌套预载入
  207. $throughList = $this->through->where($where)->select();
  208. $keys = $throughList->column($this->throughPk, $this->throughPk);
  209. if ($closure instanceof Closure) {
  210. $closure($this->query);
  211. }
  212. $list = $this->query->where($this->throughKey, 'in', $keys)->select();
  213. // 组装模型数据
  214. $data = [];
  215. $keys = $throughList->column($this->foreignKey, $this->throughPk);
  216. foreach ($list as $set) {
  217. $data[$keys[$set->{$this->throughKey}]][] = $set;
  218. }
  219. return $data;
  220. }
  221. /**
  222. * 关联统计
  223. * @access public
  224. * @param Model $result 数据对象
  225. * @param Closure $closure 闭包
  226. * @param string $aggregate 聚合查询方法
  227. * @param string $field 字段
  228. * @param string $name 统计字段别名
  229. * @return integer
  230. */
  231. public function relationCount($result, $closure, $aggregate = 'count', $field = '*', &$name = null)
  232. {
  233. $localKey = $this->localKey;
  234. if (!isset($result->$localKey)) {
  235. return 0;
  236. }
  237. if ($closure instanceof Closure) {
  238. $return = $closure($this->query);
  239. if ($return && is_string($return)) {
  240. $name = $return;
  241. }
  242. }
  243. $alias = Loader::parseName(basename(str_replace('\\', '/', $this->model)));
  244. $throughTable = $this->through->getTable();
  245. $pk = $this->throughPk;
  246. $throughKey = $this->throughKey;
  247. $modelTable = $this->parent->getTable();
  248. if (false === strpos($field, '.')) {
  249. $field = $alias . '.' . $field;
  250. }
  251. return $this->query
  252. ->alias($alias)
  253. ->join($throughTable, $throughTable . '.' . $pk . '=' . $alias . '.' . $throughKey)
  254. ->join($modelTable, $modelTable . '.' . $this->localKey . '=' . $throughTable . '.' . $this->foreignKey)
  255. ->where($throughTable . '.' . $this->foreignKey, $result->$localKey)
  256. ->$aggregate($field);
  257. }
  258. /**
  259. * 创建关联统计子查询
  260. * @access public
  261. * @param Closure $closure 闭包
  262. * @param string $aggregate 聚合查询方法
  263. * @param string $field 字段
  264. * @param string $name 统计字段别名
  265. * @return string
  266. */
  267. public function getRelationCountQuery($closure = null, $aggregate = 'count', $field = '*', &$name = null)
  268. {
  269. if ($closure instanceof Closure) {
  270. $return = $closure($this->query);
  271. if ($return && is_string($return)) {
  272. $name = $return;
  273. }
  274. }
  275. $alias = Loader::parseName(basename(str_replace('\\', '/', $this->model)));
  276. $throughTable = $this->through->getTable();
  277. $pk = $this->throughPk;
  278. $throughKey = $this->throughKey;
  279. $modelTable = $this->parent->getTable();
  280. if (false === strpos($field, '.')) {
  281. $field = $alias . '.' . $field;
  282. }
  283. return $this->query
  284. ->alias($alias)
  285. ->join($throughTable, $throughTable . '.' . $pk . '=' . $alias . '.' . $throughKey)
  286. ->join($modelTable, $modelTable . '.' . $this->localKey . '=' . $throughTable . '.' . $this->foreignKey)
  287. ->whereExp($throughTable . '.' . $this->foreignKey, '=' . $this->parent->getTable() . '.' . $this->localKey)
  288. ->fetchSql()
  289. ->$aggregate($field);
  290. }
  291. /**
  292. * 执行基础查询(仅执行一次)
  293. * @access protected
  294. * @return void
  295. */
  296. protected function baseQuery()
  297. {
  298. if (empty($this->baseQuery) && $this->parent->getData()) {
  299. $alias = Loader::parseName(basename(str_replace('\\', '/', $this->model)));
  300. $throughTable = $this->through->getTable();
  301. $pk = $this->throughPk;
  302. $throughKey = $this->throughKey;
  303. $modelTable = $this->parent->getTable();
  304. $fields = $this->getQueryFields($alias);
  305. $this->query
  306. ->field($fields)
  307. ->alias($alias)
  308. ->join($throughTable, $throughTable . '.' . $pk . '=' . $alias . '.' . $throughKey)
  309. ->join($modelTable, $modelTable . '.' . $this->localKey . '=' . $throughTable . '.' . $this->foreignKey)
  310. ->where($throughTable . '.' . $this->foreignKey, $this->parent->{$this->localKey});
  311. $this->baseQuery = true;
  312. }
  313. }
  314. }