HasMany.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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->where([
  148. $this->foreignKey => [
  149. 'exp',
  150. '=' . $this->parent->getTable() . '.' . $localKey,
  151. ],
  152. ])->fetchSql()->count();
  153. }
  154. /**
  155. * 一对多 关联模型预查询
  156. * @access public
  157. * @param object $model 关联模型对象
  158. * @param array $where 关联预查询条件
  159. * @param string $relation 关联名
  160. * @param string $subRelation 子关联
  161. * @param bool $closure
  162. * @return array
  163. */
  164. protected function eagerlyOneToMany($model, $where, $relation, $subRelation = '', $closure = false)
  165. {
  166. $foreignKey = $this->foreignKey;
  167. // 预载入关联查询 支持嵌套预载入
  168. if ($closure) {
  169. call_user_func_array($closure, [ & $model]);
  170. }
  171. $list = $model->removeWhereField($foreignKey)->where($where)->with($subRelation)->select();
  172. // 组装模型数据
  173. $data = [];
  174. foreach ($list as $set) {
  175. $data[$set->$foreignKey][] = $set;
  176. }
  177. return $data;
  178. }
  179. /**
  180. * 保存(新增)当前关联数据对象
  181. * @access public
  182. * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键
  183. * @return Model|false
  184. */
  185. public function save($data)
  186. {
  187. if ($data instanceof Model) {
  188. $data = $data->getData();
  189. }
  190. // 保存关联表数据
  191. $model = new $this->model;
  192. $data[$this->foreignKey] = $this->parent->{$this->localKey};
  193. return $model->save($data) ? $model : false;
  194. }
  195. /**
  196. * 批量保存当前关联数据对象
  197. * @access public
  198. * @param array $dataSet 数据集
  199. * @return integer
  200. */
  201. public function saveAll(array $dataSet)
  202. {
  203. $result = false;
  204. foreach ($dataSet as $key => $data) {
  205. $result = $this->save($data);
  206. }
  207. return $result;
  208. }
  209. /**
  210. * 根据关联条件查询当前模型
  211. * @access public
  212. * @param string $operator 比较操作符
  213. * @param integer $count 个数
  214. * @param string $id 关联表的统计字段
  215. * @param string $joinType JOIN类型
  216. * @return Query
  217. */
  218. public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
  219. {
  220. $table = $this->query->getTable();
  221. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  222. $relation = basename(str_replace('\\', '/', $this->model));
  223. return $this->parent->db()
  224. ->alias($model)
  225. ->field($model . '.*')
  226. ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $joinType)
  227. ->group($relation . '.' . $this->foreignKey)
  228. ->having('count(' . $id . ')' . $operator . $count);
  229. }
  230. /**
  231. * 根据关联条件查询当前模型
  232. * @access public
  233. * @param mixed $where 查询条件(数组或者闭包)
  234. * @param mixed $fields 字段
  235. * @return Query
  236. */
  237. public function hasWhere($where = [], $fields = null)
  238. {
  239. $table = $this->query->getTable();
  240. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  241. $relation = basename(str_replace('\\', '/', $this->model));
  242. if (is_array($where)) {
  243. foreach ($where as $key => $val) {
  244. if (false === strpos($key, '.')) {
  245. $where[$relation . '.' . $key] = $val;
  246. unset($where[$key]);
  247. }
  248. }
  249. }
  250. $fields = $this->getRelationQueryFields($fields, $model);
  251. return $this->parent->db()->alias($model)
  252. ->field($fields)
  253. ->group($model . '.' . $this->localKey)
  254. ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey)
  255. ->where($where);
  256. }
  257. /**
  258. * 执行基础查询(进执行一次)
  259. * @access protected
  260. * @return void
  261. */
  262. protected function baseQuery()
  263. {
  264. if (empty($this->baseQuery)) {
  265. if (isset($this->parent->{$this->localKey})) {
  266. // 关联查询带入关联条件
  267. $this->query->where($this->foreignKey, $this->parent->{$this->localKey});
  268. }
  269. $this->baseQuery = true;
  270. }
  271. }
  272. }