BelongsToMany.php 18 KB

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