BelongsToMany.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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\Collection;
  14. use think\db\Query;
  15. use think\Exception;
  16. use think\Loader;
  17. use think\Model;
  18. use think\model\Pivot;
  19. use think\model\Relation;
  20. class BelongsToMany extends Relation
  21. {
  22. // 中间表表名
  23. protected $middle;
  24. // 中间表模型名称
  25. protected $pivotName;
  26. // 中间表数据名称
  27. protected $pivotDataName = 'pivot';
  28. // 中间表模型对象
  29. protected $pivot;
  30. /**
  31. * 架构函数
  32. * @access public
  33. * @param Model $parent 上级模型对象
  34. * @param string $model 模型名
  35. * @param string $table 中间表名
  36. * @param string $foreignKey 关联模型外键
  37. * @param string $localKey 当前模型关联键
  38. */
  39. public function __construct(Model $parent, $model, $table, $foreignKey, $localKey)
  40. {
  41. $this->parent = $parent;
  42. $this->model = $model;
  43. $this->foreignKey = $foreignKey;
  44. $this->localKey = $localKey;
  45. if (false !== strpos($table, '\\')) {
  46. $this->pivotName = $table;
  47. $this->middle = basename(str_replace('\\', '/', $table));
  48. } else {
  49. $this->middle = $table;
  50. }
  51. $this->query = (new $model)->db();
  52. $this->pivot = $this->newPivot();
  53. }
  54. /**
  55. * 设置中间表模型
  56. * @access public
  57. * @param $pivot
  58. * @return $this
  59. */
  60. public function pivot($pivot)
  61. {
  62. $this->pivotName = $pivot;
  63. return $this;
  64. }
  65. /**
  66. * 设置中间表数据名称
  67. * @access public
  68. * @param string $name
  69. * @return $this
  70. */
  71. public function pivotDataName($name)
  72. {
  73. $this->pivotDataName = $name;
  74. return $this;
  75. }
  76. /**
  77. * 获取中间表更新条件
  78. * @param $data
  79. * @return array
  80. */
  81. protected function getUpdateWhere($data)
  82. {
  83. return [
  84. $this->localKey => $data[$this->localKey],
  85. $this->foreignKey => $data[$this->foreignKey],
  86. ];
  87. }
  88. /**
  89. * 实例化中间表模型
  90. * @access public
  91. * @param array $data
  92. * @param bool $isUpdate
  93. * @return Pivot
  94. * @throws Exception
  95. */
  96. protected function newPivot($data = [], $isUpdate = false)
  97. {
  98. $class = $this->pivotName ?: '\\think\\model\\Pivot';
  99. $pivot = new $class($data, $this->parent, $this->middle);
  100. if ($pivot instanceof Pivot) {
  101. return $isUpdate ? $pivot->isUpdate(true, $this->getUpdateWhere($data)) : $pivot;
  102. }
  103. throw new Exception('pivot model must extends: \think\model\Pivot');
  104. }
  105. /**
  106. * 合成中间表模型
  107. * @access protected
  108. * @param array|Collection|Paginator $models
  109. */
  110. protected function hydratePivot($models)
  111. {
  112. foreach ($models as $model) {
  113. $pivot = [];
  114. foreach ($model->getData() as $key => $val) {
  115. if (strpos($key, '__')) {
  116. list($name, $attr) = explode('__', $key, 2);
  117. if ('pivot' == $name) {
  118. $pivot[$attr] = $val;
  119. unset($model->$key);
  120. }
  121. }
  122. }
  123. $model->setRelation($this->pivotDataName, $this->newPivot($pivot, true));
  124. }
  125. }
  126. /**
  127. * 创建关联查询Query对象
  128. * @access protected
  129. * @return Query
  130. */
  131. protected function buildQuery()
  132. {
  133. $foreignKey = $this->foreignKey;
  134. $localKey = $this->localKey;
  135. // 关联查询
  136. $pk = $this->parent->getPk();
  137. $condition[] = ['pivot.' . $localKey, '=', $this->parent->$pk];
  138. return $this->belongsToManyQuery($foreignKey, $localKey, $condition);
  139. }
  140. /**
  141. * 延迟获取关联数据
  142. * @access public
  143. * @param string $subRelation 子关联名
  144. * @param \Closure $closure 闭包查询条件
  145. * @return Collection
  146. */
  147. public function getRelation($subRelation = '', $closure = null)
  148. {
  149. if ($closure instanceof Closure) {
  150. $closure($this->query);
  151. }
  152. $result = $this->buildQuery()->relation($subRelation)->select();
  153. $this->hydratePivot($result);
  154. return $result;
  155. }
  156. /**
  157. * 重载select方法
  158. * @access public
  159. * @param mixed $data
  160. * @return Collection
  161. */
  162. public function select($data = null)
  163. {
  164. $result = $this->buildQuery()->select($data);
  165. $this->hydratePivot($result);
  166. return $result;
  167. }
  168. /**
  169. * 重载paginate方法
  170. * @access public
  171. * @param null $listRows
  172. * @param bool $simple
  173. * @param array $config
  174. * @return Paginator
  175. */
  176. public function paginate($listRows = null, $simple = false, $config = [])
  177. {
  178. $result = $this->buildQuery()->paginate($listRows, $simple, $config);
  179. $this->hydratePivot($result);
  180. return $result;
  181. }
  182. /**
  183. * 重载find方法
  184. * @access public
  185. * @param mixed $data
  186. * @return Model
  187. */
  188. public function find($data = null)
  189. {
  190. $result = $this->buildQuery()->find($data);
  191. if ($result) {
  192. $this->hydratePivot([$result]);
  193. }
  194. return $result;
  195. }
  196. /**
  197. * 查找多条记录 如果不存在则抛出异常
  198. * @access public
  199. * @param array|string|Query|\Closure $data
  200. * @return Collection
  201. */
  202. public function selectOrFail($data = null)
  203. {
  204. return $this->failException(true)->select($data);
  205. }
  206. /**
  207. * 查找单条记录 如果不存在则抛出异常
  208. * @access public
  209. * @param array|string|Query|\Closure $data
  210. * @return Model
  211. */
  212. public function findOrFail($data = null)
  213. {
  214. return $this->failException(true)->find($data);
  215. }
  216. /**
  217. * 根据关联条件查询当前模型
  218. * @access public
  219. * @param string $operator 比较操作符
  220. * @param integer $count 个数
  221. * @param string $id 关联表的统计字段
  222. * @param string $joinType JOIN类型
  223. * @return Query
  224. */
  225. public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
  226. {
  227. return $this->parent;
  228. }
  229. /**
  230. * 根据关联条件查询当前模型
  231. * @access public
  232. * @param mixed $where 查询条件(数组或者闭包)
  233. * @param mixed $fields 字段
  234. * @return Query
  235. * @throws Exception
  236. */
  237. public function hasWhere($where = [], $fields = null)
  238. {
  239. throw new Exception('relation not support: hasWhere');
  240. }
  241. /**
  242. * 设置中间表的查询条件
  243. * @access public
  244. * @param string $field
  245. * @param string $op
  246. * @param mixed $condition
  247. * @return $this
  248. */
  249. public function wherePivot($field, $op = null, $condition = null)
  250. {
  251. $this->query->where('pivot.' . $field, $op, $condition);
  252. return $this;
  253. }
  254. /**
  255. * 预载入关联查询(数据集)
  256. * @access public
  257. * @param array $resultSet 数据集
  258. * @param string $relation 当前关联名
  259. * @param string $subRelation 子关联名
  260. * @param \Closure $closure 闭包
  261. * @return void
  262. */
  263. public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure)
  264. {
  265. $localKey = $this->localKey;
  266. $foreignKey = $this->foreignKey;
  267. $pk = $resultSet[0]->getPk();
  268. $range = [];
  269. foreach ($resultSet as $result) {
  270. // 获取关联外键列表
  271. if (isset($result->$pk)) {
  272. $range[] = $result->$pk;
  273. }
  274. }
  275. if (!empty($range)) {
  276. // 查询关联数据
  277. $data = $this->eagerlyManyToMany([
  278. ['pivot.' . $localKey, 'in', $range],
  279. ], $relation, $subRelation, $closure);
  280. // 关联属性名
  281. $attr = Loader::parseName($relation);
  282. // 关联数据封装
  283. foreach ($resultSet as $result) {
  284. if (!isset($data[$result->$pk])) {
  285. $data[$result->$pk] = [];
  286. }
  287. $result->setRelation($attr, $this->resultSetBuild($data[$result->$pk]));
  288. }
  289. }
  290. }
  291. /**
  292. * 预载入关联查询(单个数据)
  293. * @access public
  294. * @param Model $result 数据对象
  295. * @param string $relation 当前关联名
  296. * @param string $subRelation 子关联名
  297. * @param \Closure $closure 闭包
  298. * @return void
  299. */
  300. public function eagerlyResult(&$result, $relation, $subRelation, $closure)
  301. {
  302. $pk = $result->getPk();
  303. if (isset($result->$pk)) {
  304. $pk = $result->$pk;
  305. // 查询管理数据
  306. $data = $this->eagerlyManyToMany([
  307. ['pivot.' . $this->localKey, '=', $pk],
  308. ], $relation, $subRelation, $closure);
  309. // 关联数据封装
  310. if (!isset($data[$pk])) {
  311. $data[$pk] = [];
  312. }
  313. $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$pk]));
  314. }
  315. }
  316. /**
  317. * 关联统计
  318. * @access public
  319. * @param Model $result 数据对象
  320. * @param \Closure $closure 闭包
  321. * @param string $aggregate 聚合查询方法
  322. * @param string $field 字段
  323. * @param string $name 统计字段别名
  324. * @return integer
  325. */
  326. public function relationCount($result, $closure, $aggregate = 'count', $field = '*', &$name = '')
  327. {
  328. $pk = $result->getPk();
  329. if (!isset($result->$pk)) {
  330. return 0;
  331. }
  332. $pk = $result->$pk;
  333. if ($closure instanceof Closure) {
  334. $return = $closure($this->query);
  335. if ($return && is_string($return)) {
  336. $name = $return;
  337. }
  338. }
  339. return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [
  340. ['pivot.' . $this->localKey, '=', $pk],
  341. ])->$aggregate($field);
  342. }
  343. /**
  344. * 获取关联统计子查询
  345. * @access public
  346. * @param \Closure $closure 闭包
  347. * @param string $aggregate 聚合查询方法
  348. * @param string $field 字段
  349. * @param string $aggregateAlias 聚合字段别名
  350. * @return array
  351. */
  352. public function getRelationCountQuery($closure, $aggregate = 'count', $field = '*', &$aggregateAlias = '')
  353. {
  354. if ($closure instanceof Closure) {
  355. $return = $closure($this->query);
  356. if ($return && is_string($return)) {
  357. $aggregateAlias = $return;
  358. }
  359. }
  360. return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [
  361. [
  362. 'pivot.' . $this->localKey, 'exp', $this->query->raw('=' . $this->parent->getTable() . '.' . $this->parent->getPk()),
  363. ],
  364. ])->fetchSql()->$aggregate($field);
  365. }
  366. /**
  367. * 多对多 关联模型预查询
  368. * @access protected
  369. * @param array $where 关联预查询条件
  370. * @param string $relation 关联名
  371. * @param string $subRelation 子关联
  372. * @param \Closure $closure 闭包
  373. * @return array
  374. */
  375. protected function eagerlyManyToMany($where, $relation, $subRelation = '', $closure = null)
  376. {
  377. // 预载入关联查询 支持嵌套预载入
  378. if ($closure instanceof Closure) {
  379. $closure($this->query);
  380. }
  381. $list = $this->belongsToManyQuery($this->foreignKey, $this->localKey, $where)
  382. ->with($subRelation)
  383. ->select();
  384. // 组装模型数据
  385. $data = [];
  386. foreach ($list as $set) {
  387. $pivot = [];
  388. foreach ($set->getData() as $key => $val) {
  389. if (strpos($key, '__')) {
  390. list($name, $attr) = explode('__', $key, 2);
  391. if ('pivot' == $name) {
  392. $pivot[$attr] = $val;
  393. unset($set->$key);
  394. }
  395. }
  396. }
  397. $set->setRelation($this->pivotDataName, $this->newPivot($pivot, true));
  398. $data[$pivot[$this->localKey]][] = $set;
  399. }
  400. return $data;
  401. }
  402. /**
  403. * BELONGS TO MANY 关联查询
  404. * @access protected
  405. * @param string $foreignKey 关联模型关联键
  406. * @param string $localKey 当前模型关联键
  407. * @param array $condition 关联查询条件
  408. * @return Query
  409. */
  410. protected function belongsToManyQuery($foreignKey, $localKey, $condition = [])
  411. {
  412. // 关联查询封装
  413. $tableName = $this->query->getTable();
  414. $table = $this->pivot->getTable();
  415. $fields = $this->getQueryFields($tableName);
  416. $query = $this->query
  417. ->field($fields)
  418. ->field(true, false, $table, 'pivot', 'pivot__');
  419. if (empty($this->baseQuery)) {
  420. $relationFk = $this->query->getPk();
  421. $query->join([$table => 'pivot'], 'pivot.' . $foreignKey . '=' . $tableName . '.' . $relationFk)
  422. ->where($condition);
  423. }
  424. return $query;
  425. }
  426. /**
  427. * 保存(新增)当前关联数据对象
  428. * @access public
  429. * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键
  430. * @param array $pivot 中间表额外数据
  431. * @return array|Pivot
  432. */
  433. public function save($data, array $pivot = [])
  434. {
  435. // 保存关联表/中间表数据
  436. return $this->attach($data, $pivot);
  437. }
  438. /**
  439. * 批量保存当前关联数据对象
  440. * @access public
  441. * @param array $dataSet 数据集
  442. * @param array $pivot 中间表额外数据
  443. * @param bool $samePivot 额外数据是否相同
  444. * @return array|false
  445. */
  446. public function saveAll(array $dataSet, array $pivot = [], $samePivot = false)
  447. {
  448. $result = [];
  449. foreach ($dataSet as $key => $data) {
  450. if (!$samePivot) {
  451. $pivotData = isset($pivot[$key]) ? $pivot[$key] : [];
  452. } else {
  453. $pivotData = $pivot;
  454. }
  455. $result[] = $this->attach($data, $pivotData);
  456. }
  457. return empty($result) ? false : $result;
  458. }
  459. /**
  460. * 附加关联的一个中间表数据
  461. * @access public
  462. * @param mixed $data 数据 可以使用数组、关联模型对象 或者 关联对象的主键
  463. * @param array $pivot 中间表额外数据
  464. * @return array|Pivot
  465. * @throws Exception
  466. */
  467. public function attach($data, $pivot = [])
  468. {
  469. if (is_array($data)) {
  470. if (key($data) === 0) {
  471. $id = $data;
  472. } else {
  473. // 保存关联表数据
  474. $model = new $this->model;
  475. $id = $model->insertGetId($data);
  476. }
  477. } elseif (is_numeric($data) || is_string($data)) {
  478. // 根据关联表主键直接写入中间表
  479. $id = $data;
  480. } elseif ($data instanceof Model) {
  481. // 根据关联表主键直接写入中间表
  482. $relationFk = $data->getPk();
  483. $id = $data->$relationFk;
  484. }
  485. if ($id) {
  486. // 保存中间表数据
  487. $pk = $this->parent->getPk();
  488. $pivot[$this->localKey] = $this->parent->$pk;
  489. $ids = (array) $id;
  490. foreach ($ids as $id) {
  491. $pivot[$this->foreignKey] = $id;
  492. $this->pivot->replace()
  493. ->exists(false)
  494. ->data([])
  495. ->save($pivot);
  496. $result[] = $this->newPivot($pivot, true);
  497. }
  498. if (count($result) == 1) {
  499. // 返回中间表模型对象
  500. $result = $result[0];
  501. }
  502. return $result;
  503. } else {
  504. throw new Exception('miss relation data');
  505. }
  506. }
  507. /**
  508. * 判断是否存在关联数据
  509. * @access public
  510. * @param mixed $data 数据 可以使用关联模型对象 或者 关联对象的主键
  511. * @return Pivot
  512. * @throws Exception
  513. */
  514. public function attached($data)
  515. {
  516. if ($data instanceof Model) {
  517. $id = $data->getKey();
  518. } else {
  519. $id = $data;
  520. }
  521. $pivot = $this->pivot
  522. ->where($this->localKey, $this->parent->getKey())
  523. ->where($this->foreignKey, $id)
  524. ->find();
  525. return $pivot ?: false;
  526. }
  527. /**
  528. * 解除关联的一个中间表数据
  529. * @access public
  530. * @param integer|array $data 数据 可以使用关联对象的主键
  531. * @param bool $relationDel 是否同时删除关联表数据
  532. * @return integer
  533. */
  534. public function detach($data = null, $relationDel = false)
  535. {
  536. if (is_array($data)) {
  537. $id = $data;
  538. } elseif (is_numeric($data) || is_string($data)) {
  539. // 根据关联表主键直接写入中间表
  540. $id = $data;
  541. } elseif ($data instanceof Model) {
  542. // 根据关联表主键直接写入中间表
  543. $relationFk = $data->getPk();
  544. $id = $data->$relationFk;
  545. }
  546. // 删除中间表数据
  547. $pk = $this->parent->getPk();
  548. $pivot[] = [$this->localKey, '=', $this->parent->$pk];
  549. if (isset($id)) {
  550. $pivot[] = [$this->foreignKey, is_array($id) ? 'in' : '=', $id];
  551. }
  552. $result = $this->pivot->where($pivot)->delete();
  553. // 删除关联表数据
  554. if (isset($id) && $relationDel) {
  555. $model = $this->model;
  556. $model::destroy($id);
  557. }
  558. return $result;
  559. }
  560. /**
  561. * 数据同步
  562. * @access public
  563. * @param array $ids
  564. * @param bool $detaching
  565. * @return array
  566. */
  567. public function sync($ids, $detaching = true)
  568. {
  569. $changes = [
  570. 'attached' => [],
  571. 'detached' => [],
  572. 'updated' => [],
  573. ];
  574. $pk = $this->parent->getPk();
  575. $current = $this->pivot
  576. ->where($this->localKey, $this->parent->$pk)
  577. ->column($this->foreignKey);
  578. $records = [];
  579. foreach ($ids as $key => $value) {
  580. if (!is_array($value)) {
  581. $records[$value] = [];
  582. } else {
  583. $records[$key] = $value;
  584. }
  585. }
  586. $detach = array_diff($current, array_keys($records));
  587. if ($detaching && count($detach) > 0) {
  588. $this->detach($detach);
  589. $changes['detached'] = $detach;
  590. }
  591. foreach ($records as $id => $attributes) {
  592. if (!in_array($id, $current)) {
  593. $this->attach($id, $attributes);
  594. $changes['attached'][] = $id;
  595. } elseif (count($attributes) > 0 && $this->attach($id, $attributes)) {
  596. $changes['updated'][] = $id;
  597. }
  598. }
  599. return $changes;
  600. }
  601. /**
  602. * 执行基础查询(仅执行一次)
  603. * @access protected
  604. * @return void
  605. */
  606. protected function baseQuery()
  607. {
  608. if (empty($this->baseQuery) && $this->parent->getData()) {
  609. $pk = $this->parent->getPk();
  610. $table = $this->pivot->getTable();
  611. $this->query
  612. ->join([$table => 'pivot'], 'pivot.' . $this->foreignKey . '=' . $this->query->getTable() . '.' . $this->query->getPk())
  613. ->where('pivot.' . $this->localKey, $this->parent->$pk);
  614. $this->baseQuery = true;
  615. }
  616. }
  617. }