HasMany.php 11 KB

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