MorphMany.php 9.6 KB

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