HasMany.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. if (get_class($parent) == $model) {
  34. $this->selfRelation = true;
  35. }
  36. }
  37. /**
  38. * 延迟获取关联数据
  39. * @access public
  40. * @param string $subRelation 子关联名
  41. * @param \Closure $closure 闭包查询条件
  42. * @return \think\Collection
  43. */
  44. public function getRelation($subRelation = '', $closure = null)
  45. {
  46. if ($closure) {
  47. $closure($this->query);
  48. }
  49. $list = $this->query
  50. ->where($this->foreignKey, $this->parent->{$this->localKey})
  51. ->relation($subRelation)
  52. ->select();
  53. $parent = clone $this->parent;
  54. foreach ($list as &$model) {
  55. $model->setParent($parent);
  56. }
  57. return $list;
  58. }
  59. /**
  60. * 预载入关联查询
  61. * @access public
  62. * @param array $resultSet 数据集
  63. * @param string $relation 当前关联名
  64. * @param string $subRelation 子关联名
  65. * @param \Closure $closure 闭包
  66. * @return void
  67. */
  68. public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure)
  69. {
  70. $localKey = $this->localKey;
  71. $range = [];
  72. foreach ($resultSet as $result) {
  73. // 获取关联外键列表
  74. if (isset($result->$localKey)) {
  75. $range[] = $result->$localKey;
  76. }
  77. }
  78. if (!empty($range)) {
  79. $where = [
  80. [$this->foreignKey, 'in', $range],
  81. ];
  82. $data = $this->eagerlyOneToMany($where, $relation, $subRelation, $closure);
  83. // 关联属性名
  84. $attr = Loader::parseName($relation);
  85. // 关联数据封装
  86. foreach ($resultSet as $result) {
  87. $pk = $result->$localKey;
  88. if (!isset($data[$pk])) {
  89. $data[$pk] = [];
  90. }
  91. foreach ($data[$pk] as &$relationModel) {
  92. $relationModel->setParent(clone $result);
  93. }
  94. $result->setRelation($attr, $this->resultSetBuild($data[$pk]));
  95. }
  96. }
  97. }
  98. /**
  99. * 预载入关联查询
  100. * @access public
  101. * @param Model $result 数据对象
  102. * @param string $relation 当前关联名
  103. * @param string $subRelation 子关联名
  104. * @param \Closure $closure 闭包
  105. * @return void
  106. */
  107. public function eagerlyResult(&$result, $relation, $subRelation, $closure)
  108. {
  109. $localKey = $this->localKey;
  110. if (isset($result->$localKey)) {
  111. $pk = $result->$localKey;
  112. $where = [
  113. [$this->foreignKey, '=', $pk],
  114. ];
  115. $data = $this->eagerlyOneToMany($where, $relation, $subRelation, $closure);
  116. // 关联数据封装
  117. if (!isset($data[$pk])) {
  118. $data[$pk] = [];
  119. }
  120. foreach ($data[$pk] as &$relationModel) {
  121. $relationModel->setParent(clone $result);
  122. }
  123. $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$pk]));
  124. }
  125. }
  126. /**
  127. * 关联统计
  128. * @access public
  129. * @param Model $result 数据对象
  130. * @param \Closure $closure 闭包
  131. * @param string $aggregate 聚合查询方法
  132. * @param string $field 字段
  133. * @param string $name 统计字段别名
  134. * @return integer
  135. */
  136. public function relationCount($result, $closure, $aggregate = 'count', $field = '*', &$name = '')
  137. {
  138. $localKey = $this->localKey;
  139. if (!isset($result->$localKey)) {
  140. return 0;
  141. }
  142. if ($closure) {
  143. $return = $closure($this->query);
  144. if ($return && is_string($return)) {
  145. $name = $return;
  146. }
  147. }
  148. return $this->query
  149. ->where($this->foreignKey, '=', $result->$localKey)
  150. ->$aggregate($field);
  151. }
  152. /**
  153. * 创建关联统计子查询
  154. * @access public
  155. * @param \Closure $closure 闭包
  156. * @param string $aggregate 聚合查询方法
  157. * @param string $field 字段
  158. * @param string $aggregateAlias 聚合字段别名
  159. * @return string
  160. */
  161. public function getRelationCountQuery($closure, $aggregate = 'count', $field = '*', &$aggregateAlias = '')
  162. {
  163. if ($closure) {
  164. $return = $closure($this->query);
  165. if ($return && is_string($return)) {
  166. $aggregateAlias = $return;
  167. }
  168. }
  169. return $this->query->alias($aggregate . '_table')
  170. ->whereExp($aggregate . '_table.' . $this->foreignKey, '=' . $this->parent->getTable() . '.' . $this->localKey)
  171. ->fetchSql()
  172. ->$aggregate($field);
  173. }
  174. /**
  175. * 一对多 关联模型预查询
  176. * @access public
  177. * @param array $where 关联预查询条件
  178. * @param string $relation 关联名
  179. * @param string $subRelation 子关联
  180. * @param \Closure $closure
  181. * @return array
  182. */
  183. protected function eagerlyOneToMany($where, $relation, $subRelation = '', $closure = null)
  184. {
  185. $foreignKey = $this->foreignKey;
  186. $this->query->removeWhereField($this->foreignKey);
  187. // 预载入关联查询 支持嵌套预载入
  188. if ($closure) {
  189. $closure($this->query);
  190. }
  191. $list = $this->query->where($where)->with($subRelation)->select();
  192. // 组装模型数据
  193. $data = [];
  194. foreach ($list as $set) {
  195. $data[$set->$foreignKey][] = $set;
  196. }
  197. return $data;
  198. }
  199. /**
  200. * 保存(新增)当前关联数据对象
  201. * @access public
  202. * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键
  203. * @param boolean $replace 是否自动识别更新和写入
  204. * @return Model|false
  205. */
  206. public function save($data, $replace = true)
  207. {
  208. $model = $this->make();
  209. return $model->replace($replace)->save($data) ? $model : false;
  210. }
  211. /**
  212. * 创建关联对象实例
  213. * @param array $data
  214. * @return Model
  215. */
  216. public function make($data = [])
  217. {
  218. if ($data instanceof Model) {
  219. $data = $data->getData();
  220. }
  221. // 保存关联表数据
  222. $data[$this->foreignKey] = $this->parent->{$this->localKey};
  223. return new $this->model($data);
  224. }
  225. /**
  226. * 批量保存当前关联数据对象
  227. * @access public
  228. * @param array|\think\Collection $dataSet 数据集
  229. * @param boolean $replace 是否自动识别更新和写入
  230. * @return array|false
  231. */
  232. public function saveAll($dataSet, $replace = true)
  233. {
  234. $result = [];
  235. foreach ($dataSet as $key => $data) {
  236. $result[] = $this->save($data, $replace);
  237. }
  238. return empty($result) ? false : $result;
  239. }
  240. /**
  241. * 根据关联条件查询当前模型
  242. * @access public
  243. * @param string $operator 比较操作符
  244. * @param integer $count 个数
  245. * @param string $id 关联表的统计字段
  246. * @param string $joinType JOIN类型
  247. * @return Query
  248. */
  249. public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
  250. {
  251. $table = $this->query->getTable();
  252. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  253. $relation = basename(str_replace('\\', '/', $this->model));
  254. $softDelete = $this->query->getOptions('soft_delete');
  255. return $this->parent->db()
  256. ->alias($model)
  257. ->field($model . '.*')
  258. ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $joinType)
  259. ->when($softDelete, function ($query) use ($softDelete, $relation) {
  260. $query->where($relation . strstr($softDelete[0], '.'), '=' == $softDelete[1][0] ? $softDelete[1][1] : null);
  261. })
  262. ->group($relation . '.' . $this->foreignKey)
  263. ->having('count(' . $id . ')' . $operator . $count);
  264. }
  265. /**
  266. * 根据关联条件查询当前模型
  267. * @access public
  268. * @param mixed $where 查询条件(数组或者闭包)
  269. * @param mixed $fields 字段
  270. * @return Query
  271. */
  272. public function hasWhere($where = [], $fields = null)
  273. {
  274. $table = $this->query->getTable();
  275. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  276. $relation = basename(str_replace('\\', '/', $this->model));
  277. if (is_array($where)) {
  278. $this->getQueryWhere($where, $relation);
  279. }
  280. $fields = $this->getRelationQueryFields($fields, $model);
  281. $softDelete = $this->query->getOptions('soft_delete');
  282. return $this->parent->db()
  283. ->alias($model)
  284. ->group($model . '.' . $this->localKey)
  285. ->field($fields)
  286. ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey)
  287. ->when($softDelete, function ($query) use ($softDelete, $relation) {
  288. $query->where($relation . strstr($softDelete[0], '.'), '=' == $softDelete[1][0] ? $softDelete[1][1] : null);
  289. })
  290. ->where($where);
  291. }
  292. /**
  293. * 执行基础查询(仅执行一次)
  294. * @access protected
  295. * @return void
  296. */
  297. protected function baseQuery()
  298. {
  299. if (empty($this->baseQuery)) {
  300. if (isset($this->parent->{$this->localKey})) {
  301. // 关联查询带入关联条件
  302. $this->query->where($this->foreignKey, '=', $this->parent->{$this->localKey});
  303. }
  304. $this->baseQuery = true;
  305. }
  306. }
  307. }