HasMany.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 think\db\Query;
  13. use think\Loader;
  14. use think\Model;
  15. use think\model\Relation;
  16. class HasMany extends Relation
  17. {
  18. /**
  19. * 构造函数
  20. * @access public
  21. * @param Model $parent 上级模型对象
  22. * @param string $model 模型名
  23. * @param string $foreignKey 关联外键
  24. * @param string $localKey 当前模型主键
  25. */
  26. public function __construct(Model $parent, $model, $foreignKey, $localKey)
  27. {
  28. $this->parent = $parent;
  29. $this->model = $model;
  30. $this->foreignKey = $foreignKey;
  31. $this->localKey = $localKey;
  32. $this->query = (new $model)->db();
  33. }
  34. /**
  35. * 延迟获取关联数据
  36. * @param string $subRelation 子关联名
  37. * @param \Closure $closure 闭包查询条件
  38. * @return false|\PDOStatement|string|\think\Collection
  39. */
  40. public function getRelation($subRelation = '', $closure = null)
  41. {
  42. if ($closure) {
  43. call_user_func_array($closure, [ & $this->query]);
  44. }
  45. $list = $this->relation($subRelation)->select();
  46. $parent = clone $this->parent;
  47. foreach ($list as &$model) {
  48. $model->setParent($parent);
  49. }
  50. return $list;
  51. }
  52. /**
  53. * 预载入关联查询
  54. * @access public
  55. * @param array $resultSet 数据集
  56. * @param string $relation 当前关联名
  57. * @param string $subRelation 子关联名
  58. * @param \Closure $closure 闭包
  59. * @return void
  60. */
  61. public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure)
  62. {
  63. $localKey = $this->localKey;
  64. $range = [];
  65. foreach ($resultSet as $result) {
  66. // 获取关联外键列表
  67. if (isset($result->$localKey)) {
  68. $range[] = $result->$localKey;
  69. }
  70. }
  71. if (!empty($range)) {
  72. $data = $this->eagerlyOneToMany($this->query, [
  73. $this->foreignKey => [
  74. 'in',
  75. $range,
  76. ],
  77. ], $relation, $subRelation, $closure);
  78. // 关联属性名
  79. $attr = Loader::parseName($relation);
  80. // 关联数据封装
  81. foreach ($resultSet as $result) {
  82. if (!isset($data[$result->$localKey])) {
  83. $data[$result->$localKey] = [];
  84. }
  85. foreach ($data[$result->$localKey] as &$relationModel) {
  86. $relationModel->setParent(clone $result);
  87. }
  88. $result->setRelation($attr, $this->resultSetBuild($data[$result->$localKey]));
  89. }
  90. }
  91. }
  92. /**
  93. * 预载入关联查询
  94. * @access public
  95. * @param Model $result 数据对象
  96. * @param string $relation 当前关联名
  97. * @param string $subRelation 子关联名
  98. * @param \Closure $closure 闭包
  99. * @return void
  100. */
  101. public function eagerlyResult(&$result, $relation, $subRelation, $closure)
  102. {
  103. $localKey = $this->localKey;
  104. if (isset($result->$localKey)) {
  105. $data = $this->eagerlyOneToMany($this->query, [$this->foreignKey => $result->$localKey], $relation, $subRelation, $closure);
  106. // 关联数据封装
  107. if (!isset($data[$result->$localKey])) {
  108. $data[$result->$localKey] = [];
  109. }
  110. foreach ($data[$result->$localKey] as &$relationModel) {
  111. $relationModel->setParent(clone $result);
  112. }
  113. $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$result->$localKey]));
  114. }
  115. }
  116. /**
  117. * 关联统计
  118. * @access public
  119. * @param Model $result 数据对象
  120. * @param \Closure $closure 闭包
  121. * @return integer
  122. */
  123. public function relationCount($result, $closure)
  124. {
  125. $localKey = $this->localKey;
  126. $count = 0;
  127. if (isset($result->$localKey)) {
  128. if ($closure) {
  129. call_user_func_array($closure, [ & $this->query]);
  130. }
  131. $count = $this->query->where($this->foreignKey, $result->$localKey)->count();
  132. }
  133. return $count;
  134. }
  135. /**
  136. * 创建关联统计子查询
  137. * @access public
  138. * @param \Closure $closure 闭包
  139. * @return string
  140. */
  141. public function getRelationCountQuery($closure)
  142. {
  143. if ($closure) {
  144. call_user_func_array($closure, [ & $this->query]);
  145. }
  146. $localKey = $this->localKey ?: $this->parent->getPk();
  147. return $this->query->whereExp($this->foreignKey, '=' . $this->parent->getTable() . '.' . $localKey)->fetchSql()->count();
  148. }
  149. /**
  150. * 一对多 关联模型预查询
  151. * @access public
  152. * @param object $model 关联模型对象
  153. * @param array $where 关联预查询条件
  154. * @param string $relation 关联名
  155. * @param string $subRelation 子关联
  156. * @param bool $closure
  157. * @return array
  158. */
  159. protected function eagerlyOneToMany($model, $where, $relation, $subRelation = '', $closure = false)
  160. {
  161. $foreignKey = $this->foreignKey;
  162. // 预载入关联查询 支持嵌套预载入
  163. if ($closure) {
  164. call_user_func_array($closure, [ & $model]);
  165. }
  166. $list = $model->removeWhereField($foreignKey)->where($where)->with($subRelation)->select();
  167. // 组装模型数据
  168. $data = [];
  169. foreach ($list as $set) {
  170. $data[$set->$foreignKey][] = $set;
  171. }
  172. return $data;
  173. }
  174. /**
  175. * 保存(新增)当前关联数据对象
  176. * @access public
  177. * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键
  178. * @return Model|false
  179. */
  180. public function save($data)
  181. {
  182. if ($data instanceof Model) {
  183. $data = $data->getData();
  184. }
  185. // 保存关联表数据
  186. $model = new $this->model;
  187. $data[$this->foreignKey] = $this->parent->{$this->localKey};
  188. return $model->save($data) ? $model : false;
  189. }
  190. /**
  191. * 批量保存当前关联数据对象
  192. * @access public
  193. * @param array $dataSet 数据集
  194. * @return integer
  195. */
  196. public function saveAll(array $dataSet)
  197. {
  198. $result = false;
  199. foreach ($dataSet as $key => $data) {
  200. $result = $this->save($data);
  201. }
  202. return $result;
  203. }
  204. /**
  205. * 根据关联条件查询当前模型
  206. * @access public
  207. * @param string $operator 比较操作符
  208. * @param integer $count 个数
  209. * @param string $id 关联表的统计字段
  210. * @param string $joinType JOIN类型
  211. * @return Query
  212. */
  213. public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
  214. {
  215. $table = $this->query->getTable();
  216. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  217. $relation = basename(str_replace('\\', '/', $this->model));
  218. return $this->parent->db()
  219. ->alias($model)
  220. ->field($model . '.*')
  221. ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $joinType)
  222. ->group($relation . '.' . $this->foreignKey)
  223. ->having('count(' . $id . ')' . $operator . $count);
  224. }
  225. /**
  226. * 根据关联条件查询当前模型
  227. * @access public
  228. * @param mixed $where 查询条件(数组或者闭包)
  229. * @param mixed $fields 字段
  230. * @return Query
  231. */
  232. public function hasWhere($where = [], $fields = null)
  233. {
  234. $table = $this->query->getTable();
  235. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  236. $relation = basename(str_replace('\\', '/', $this->model));
  237. if (is_array($where)) {
  238. foreach ($where as $key => $val) {
  239. if (false === strpos($key, '.')) {
  240. $where[$relation . '.' . $key] = $val;
  241. unset($where[$key]);
  242. }
  243. }
  244. }
  245. $fields = $this->getRelationQueryFields($fields, $model);
  246. return $this->parent->db()->alias($model)
  247. ->field($fields)
  248. ->group($model . '.' . $this->localKey)
  249. ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey)
  250. ->where($where);
  251. }
  252. /**
  253. * 执行基础查询(进执行一次)
  254. * @access protected
  255. * @return void
  256. */
  257. protected function baseQuery()
  258. {
  259. if (empty($this->baseQuery)) {
  260. if (isset($this->parent->{$this->localKey})) {
  261. // 关联查询带入关联条件
  262. $this->query->where($this->foreignKey, $this->parent->{$this->localKey});
  263. }
  264. $this->baseQuery = true;
  265. }
  266. }
  267. }