当前路径:vendor/topthink/think-orm/src/model/relation/BelongsToMany.php <?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- namespace think\model\relation; use Closure; use think\Collection; use think\db\BaseQuery as Query; use think\db\exception\DbException as Exception; use think\db\Raw; use think\Model; use think\model\Pivot; use think\model\Relation; use think\Paginator; /** * 澶氬澶氬叧鑱旂被 */ class BelongsToMany extends Relation { /** * 涓棿琛ㄨ〃鍚? * @var string */ protected $middle; /** * 涓棿琛ㄦā鍨嬪悕绉? * @var string */ protected $pivotName; /** * 涓棿琛ㄦā鍨嬪璞? * @var Pivot */ protected $pivot; /** * 涓棿琛ㄦ暟鎹悕绉? * @var string */ protected $pivotDataName = 'pivot'; /** * 鏋舵瀯鍑芥暟 * @access public * @param Model $parent 涓婄骇妯″瀷瀵硅薄 * @param string $model 妯″瀷鍚? * @param string $middle 涓棿琛?妯″瀷鍚? * @param string $foreignKey 鍏宠仈妯″瀷澶栭敭 * @param string $localKey 褰撳墠妯″瀷鍏宠仈閿? */ public function __construct(Model $parent, string $model, string $middle, string $foreignKey, string $localKey) { $this->parent = $parent; $this->model = $model; $this->foreignKey = $foreignKey; $this->localKey = $localKey; if (false !== strpos($middle, '\\')) { $this->pivotName = $middle; $this->middle = class_basename($middle); } else { $this->middle = $middle; } $this->query = (new $model)->db(); $this->pivot = $this->newPivot(); } /** * 璁剧疆涓棿琛ㄦā鍨? * @access public * @param $pivot * @return $this */ public function pivot(string $pivot) { $this->pivotName = $pivot; return $this; } /** * 璁剧疆涓棿琛ㄦ暟鎹悕绉? * @access public * @param string $name * @return $this */ public function name(string $name) { $this->pivotDataName = $name; return $this; } /** * 瀹炰緥鍖栦腑闂磋〃妯″瀷 * @access public * @param $data * @return Pivot * @throws Exception */ protected function newPivot(array $data = []): Pivot { $class = $this->pivotName ?: Pivot::class; $pivot = new $class($data, $this->parent, $this->middle); if ($pivot instanceof Pivot) { return $pivot; } else { throw new Exception('pivot model must extends: \think\model\Pivot'); } } /** * 鍚堟垚涓棿琛ㄦā鍨? * @access protected * @param array|Collection|Paginator $models */ protected function hydratePivot(iterable $models) { foreach ($models as $model) { $pivot = []; foreach ($model->getData() as $key => $val) { if (strpos($key, '__')) { [$name, $attr] = explode('__', $key, 2); if ('pivot' == $name) { $pivot[$attr] = $val; unset($model->$key); } } } $model->setRelation($this->pivotDataName, $this->newPivot($pivot)); } } /** * 寤惰繜鑾峰彇鍏宠仈鏁版嵁 * @access public * @param array $subRelation 瀛愬叧鑱斿悕 * @param Closure $closure 闂寘鏌ヨ鏉′欢 * @return Collection */ public function getRelation(array $subRelation = [], Closure $closure = null): Collection { if ($closure) { $closure($this->getClosureType($closure)); } $result = $this->relation($subRelation) ->select() ->setParent(clone $this->parent); $this->hydratePivot($result); return $result; } /** * 閲嶈浇select鏂规硶 * @access public * @param mixed $data * @return Collection */ public function select($data = null): Collection { $this->baseQuery(); $result = $this->query->select($data); $this->hydratePivot($result); return $result; } /** * 閲嶈浇paginate鏂规硶 * @access public * @param int|array $listRows * @param int|bool $simple * @return Paginator */ public function paginate($listRows = null, $simple = false): Paginator { $this->baseQuery(); $result = $this->query->paginate($listRows, $simple); $this->hydratePivot($result); return $result; } /** * 閲嶈浇find鏂规硶 * @access public * @param mixed $data * @return Model */ public function find($data = null) { $this->baseQuery(); $result = $this->query->find($data); if ($result && !$result->isEmpty()) { $this->hydratePivot([$result]); } return $result; } /** * 鏍规嵁鍏宠仈鏉′欢鏌ヨ褰撳墠妯″瀷 * @access public * @param string $operator 姣旇緝鎿嶄綔绗? * @param integer $count 涓暟 * @param string $id 鍏宠仈琛ㄧ殑缁熻瀛楁 * @param string $joinType JOIN绫诲瀷 * @param Query $query Query瀵硅薄 * @return Model */ public function has(string $operator = '>=', $count = 1, $id = '*', string $joinType = 'INNER', Query $query = null) { return $this->parent; } /** * 鏍规嵁鍏宠仈鏉′欢鏌ヨ褰撳墠妯″瀷 * @access public * @param mixed $where 鏌ヨ鏉′欢锛堟暟缁勬垨鑰呴棴鍖咃級 * @param mixed $fields 瀛楁 * @param string $joinType JOIN绫诲瀷 * @param Query $query Query瀵硅薄 * @return Query * @throws Exception */ public function hasWhere($where = [], $fields = null, string $joinType = '', Query $query = null) { throw new Exception('relation not support: hasWhere'); } /** * 璁剧疆涓棿琛ㄧ殑鏌ヨ鏉′欢 * @access public * @param string $field * @param string $op * @param mixed $condition * @return $this */ public function wherePivot($field, $op = null, $condition = null) { $this->query->where('pivot.' . $field, $op, $condition); return $this; } /** * 棰勮浇鍏ュ叧鑱旀煡璇紙鏁版嵁闆嗭級 * @access public * @param array $resultSet 鏁版嵁闆? * @param string $relation 褰撳墠鍏宠仈鍚? * @param array $subRelation 瀛愬叧鑱斿悕 * @param Closure $closure 闂寘 * @param array $cache 鍏宠仈缂撳瓨 * @return void */ public function eagerlyResultSet(array &$resultSet, string $relation, array $subRelation, Closure $closure = null, array $cache = []): void { $localKey = $this->localKey; $pk = $resultSet[0]->getPk(); $range = []; foreach ($resultSet as $result) { // 鑾峰彇鍏宠仈澶栭敭鍒楄〃 if (isset($result->$pk)) { $range[] = $result->$pk; } } if (!empty($range)) { // 鏌ヨ鍏宠仈鏁版嵁 $data = $this->eagerlyManyToMany([ ['pivot.' . $localKey, 'in', $range], ], $subRelation, $closure, $cache); // 鍏宠仈鏁版嵁灏佽 foreach ($resultSet as $result) { if (!isset($data[$result->$pk])) { $data[$result->$pk] = []; } $result->setRelation($relation, $this->resultSetBuild($data[$result->$pk], clone $this->parent)); } } } /** * 棰勮浇鍏ュ叧鑱旀煡璇紙鍗曚釜鏁版嵁锛? * @access public * @param Model $result 鏁版嵁瀵硅薄 * @param string $relation 褰撳墠鍏宠仈鍚? * @param array $subRelation 瀛愬叧鑱斿悕 * @param Closure $closure 闂寘 * @param array $cache 鍏宠仈缂撳瓨 * @return void */ public function eagerlyResult(Model $result, string $relation, array $subRelation, Closure $closure = null, array $cache = []): void { $pk = $result->getPk(); if (isset($result->$pk)) { $pk = $result->$pk; // 鏌ヨ绠$悊鏁版嵁 $data = $this->eagerlyManyToMany([ ['pivot.' . $this->localKey, '=', $pk], ], $subRelation, $closure, $cache); // 鍏宠仈鏁版嵁灏佽 if (!isset($data[$pk])) { $data[$pk] = []; } $result->setRelation($relation, $this->resultSetBuild($data[$pk], clone $this->parent)); } } /** * 鍏宠仈缁熻 * @access public * @param Model $result 鏁版嵁瀵硅薄 * @param Closure $closure 闂寘 * @param string $aggregate 鑱氬悎鏌ヨ鏂规硶 * @param string $field 瀛楁 * @param string $name 缁熻瀛楁鍒悕 * @return integer */ public function relationCount(Model $result, Closure $closure = null, string $aggregate = 'count', string $field = '*', string &$name = null): float { $pk = $result->getPk(); if (!isset($result->$pk)) { return 0; } $pk = $result->$pk; if ($closure) { $closure($this->getClosureType($closure), $name); } return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [ ['pivot.' . $this->localKey, '=', $pk], ])->$aggregate($field); } /** * 鑾峰彇鍏宠仈缁熻瀛愭煡璇? * @access public * @param Closure $closure 闂寘 * @param string $aggregate 鑱氬悎鏌ヨ鏂规硶 * @param string $field 瀛楁 * @param string $name 缁熻瀛楁鍒悕 * @return string */ public function getRelationCountQuery(Closure $closure = null, string $aggregate = 'count', string $field = '*', string &$name = null): string { if ($closure) { $closure($this->getClosureType($closure), $name); } return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [ [ 'pivot.' . $this->localKey, 'exp', new Raw('=' . $this->parent->db(false)->getTable() . '.' . $this->parent->getPk()), ], ])->fetchSql()->$aggregate($field); } /** * 澶氬澶?鍏宠仈妯″瀷棰勬煡璇? * @access protected * @param array $where 鍏宠仈棰勬煡璇㈡潯浠? * @param array $subRelation 瀛愬叧鑱? * @param Closure $closure 闂寘 * @param array $cache 鍏宠仈缂撳瓨 * @return array */ protected function eagerlyManyToMany(array $where, array $subRelation = [], Closure $closure = null, array $cache = []): array { if ($closure) { $closure($this->getClosureType($closure)); } // 棰勮浇鍏ュ叧鑱旀煡璇?鏀寔宓屽棰勮浇鍏? $list = $this->belongsToManyQuery($this->foreignKey, $this->localKey, $where) ->with($subRelation) ->cache($cache[0] ?? false, $cache[1] ?? null, $cache[2] ?? null) ->select(); // 缁勮妯″瀷鏁版嵁 $data = []; foreach ($list as $set) { $pivot = []; foreach ($set->getData() as $key => $val) { if (strpos($key, '__')) { [$name, $attr] = explode('__', $key, 2); if ('pivot' == $name) { $pivot[$attr] = $val; unset($set->$key); } } } $key = $pivot[$this->localKey]; if ($this->withLimit && isset($data[$key]) && count($data[$key]) >= $this->withLimit) { continue; } $set->setRelation($this->pivotDataName, $this->newPivot($pivot)); $data[$key][] = $set; } return $data; } /** * BELONGS TO MANY 鍏宠仈鏌ヨ * @access protected * @param string $foreignKey 鍏宠仈妯″瀷鍏宠仈閿? * @param string $localKey 褰撳墠妯″瀷鍏宠仈閿? * @param array $condition 鍏宠仈鏌ヨ鏉′欢 * @return Query */ protected function belongsToManyQuery(string $foreignKey, string $localKey, array $condition = []): Query { // 鍏宠仈鏌ヨ灏佽 if (empty($this->baseQuery)) { $tableName = $this->query->getTable(); $table = $this->pivot->db()->getTable(); $fields = $this->getQueryFields($tableName); if ($this->withLimit) { $this->query->limit($this->withLimit); } $this->query ->field($fields) ->tableField(true, $table, 'pivot', 'pivot__') ->join([$table => 'pivot'], 'pivot.' . $foreignKey . '=' . $tableName . '.' . $this->query->getPk()) ->where($condition); } return $this->query; } /** * 淇濆瓨锛堟柊澧烇級褰撳墠鍏宠仈鏁版嵁瀵硅薄 * @access public * @param mixed $data 鏁版嵁 鍙互浣跨敤鏁扮粍 鍏宠仈妯″瀷瀵硅薄 鍜?鍏宠仈瀵硅薄鐨勪富閿? * @param array $pivot 涓棿琛ㄩ澶栨暟鎹? * @return array|Pivot */ public function save($data, array $pivot = []) { // 淇濆瓨鍏宠仈琛?涓棿琛ㄦ暟鎹? return $this->attach($data, $pivot); } /** * 鎵归噺淇濆瓨褰撳墠鍏宠仈鏁版嵁瀵硅薄 * @access public * @param iterable $dataSet 鏁版嵁闆? * @param array $pivot 涓棿琛ㄩ澶栨暟鎹? * @param bool $samePivot 棰濆鏁版嵁鏄惁鐩稿悓 * @return array|false */ public function saveAll(iterable $dataSet, array $pivot = [], bool $samePivot = false) { $result = []; foreach ($dataSet as $key => $data) { if (!$samePivot) { $pivotData = $pivot[$key] ?? []; } else { $pivotData = $pivot; } $result[] = $this->attach($data, $pivotData); } return empty($result) ? false : $result; } /** * 闄勫姞鍏宠仈鐨勪竴涓腑闂磋〃鏁版嵁 * @access public * @param mixed $data 鏁版嵁 鍙互浣跨敤鏁扮粍銆佸叧鑱旀ā鍨嬪璞?鎴栬€?鍏宠仈瀵硅薄鐨勪富閿? * @param array $pivot 涓棿琛ㄩ澶栨暟鎹? * @return array|Pivot * @throws Exception */ public function attach($data, array $pivot = []) { if (is_array($data)) { if (key($data) === 0) { $id = $data; } else { // 淇濆瓨鍏宠仈琛ㄦ暟鎹? $model = new $this->model; $id = $model->insertGetId($data); } } elseif (is_numeric($data) || is_string($data)) { // 鏍规嵁鍏宠仈琛ㄤ富閿洿鎺ュ啓鍏ヤ腑闂磋〃 $id = $data; } elseif ($data instanceof Model) { // 鏍规嵁鍏宠仈琛ㄤ富閿洿鎺ュ啓鍏ヤ腑闂磋〃 $id = $data->getKey(); } if (!empty($id)) { // 淇濆瓨涓棿琛ㄦ暟鎹? $pivot[$this->localKey] = $this->parent->getKey(); $ids = (array) $id; foreach ($ids as $id) { $pivot[$this->foreignKey] = $id; $this->pivot->replace() ->exists(false) ->data([]) ->save($pivot); $result[] = $this->newPivot($pivot); } if (count($result) == 1) { // 杩斿洖涓棿琛ㄦā鍨嬪璞? $result = $result[0]; } return $result; } else { throw new Exception('miss relation data'); } } /** * 鍒ゆ柇鏄惁瀛樺湪鍏宠仈鏁版嵁 * @access public * @param mixed $data 鏁版嵁 鍙互浣跨敤鍏宠仈妯″瀷瀵硅薄 鎴栬€?鍏宠仈瀵硅薄鐨勪富閿? * @return Pivot|false */ public function attached($data) { if ($data instanceof Model) { $id = $data->getKey(); } else { $id = $data; } $pivot = $this->pivot ->where($this->localKey, $this->parent->getKey()) ->where($this->foreignKey, $id) ->find(); return $pivot ?: false; } /** * 瑙i櫎鍏宠仈鐨勪竴涓腑闂磋〃鏁版嵁 * @access public * @param integer|array $data 鏁版嵁 鍙互浣跨敤鍏宠仈瀵硅薄鐨勪富閿? * @param bool $relationDel 鏄惁鍚屾椂鍒犻櫎鍏宠仈琛ㄦ暟鎹? * @return integer */ public function detach($data = null, bool $relationDel = false): int { if (is_array($data)) { $id = $data; } elseif (is_numeric($data) || is_string($data)) { // 鏍规嵁鍏宠仈琛ㄤ富閿洿鎺ュ啓鍏ヤ腑闂磋〃 $id = $data; } elseif ($data instanceof Model) { // 鏍规嵁鍏宠仈琛ㄤ富閿洿鎺ュ啓鍏ヤ腑闂磋〃 $id = $data->getKey(); } // 鍒犻櫎涓棿琛ㄦ暟鎹? $pivot = []; $pivot[] = [$this->localKey, '=', $this->parent->getKey()]; if (isset($id)) { $pivot[] = [$this->foreignKey, is_array($id) ? 'in' : '=', $id]; } $result = $this->pivot->where($pivot)->delete(); // 鍒犻櫎鍏宠仈琛ㄦ暟鎹? if (isset($id) && $relationDel) { $model = $this->model; $model::destroy($id); } return $result; } /** * 鏁版嵁鍚屾 * @access public * @param array $ids * @param bool $detaching * @return array */ public function sync(array $ids, bool $detaching = true): array { $changes = [ 'attached' => [], 'detached' => [], 'updated' => [], ]; $current = $this->pivot ->where($this->localKey, $this->parent->getKey()) ->column($this->foreignKey); $records = []; foreach ($ids as $key => $value) { if (!is_array($value)) { $records[$value] = []; } else { $records[$key] = $value; } } $detach = array_diff($current, array_keys($records)); if ($detaching && count($detach) > 0) { $this->detach($detach); $changes['detached'] = $detach; } foreach ($records as $id => $attributes) { if (!in_array($id, $current)) { $this->attach($id, $attributes); $changes['attached'][] = $id; } elseif (count($attributes) > 0 && $this->attach($id, $attributes)) { $changes['updated'][] = $id; } } return $changes; } /** * 鎵ц鍩虹鏌ヨ锛堜粎鎵ц涓€娆★級 * @access protected * @return void */ protected function baseQuery(): void { if (empty($this->baseQuery)) { $foreignKey = $this->foreignKey; $localKey = $this->localKey; // 鍏宠仈鏌ヨ if (null === $this->parent->getKey()) { $condition = ['pivot.' . $localKey, 'exp', new Raw('=' . $this->parent->getTable() . '.' . $this->parent->getPk())]; } else { $condition = ['pivot.' . $localKey, '=', $this->parent->getKey()]; } $this->belongsToManyQuery($foreignKey, $localKey, [$condition]); $this->baseQuery = true; } } }
相关源码
- 可旋转的彩色立方体C#源代码2021-10-29
- 在线考试系统2021-10-15
- EduSoho开源网校系统源码2019-06-27
- 仿拼多多小程序商城源码2019-06-06
- PHP5网站运行监测系统源码2017-04-14
关于我们 | 顾问团队 | 发展历程 | 联系我们 | 源码上传
联系电话(Tel):4008-010-151(免长途)
地址:北京市海淀区大恒科技大厦五层 邮编:100080
Floor 5th,Daheng Building,Zhongguancun,Beijing,China,100080
51Aspx.com 版权所有 CopyRight © 2006-2022. 京ICP备09089570号 | 京公网安备11010702000869号
联系电话(Tel):4008-010-151(免长途)
地址:北京市海淀区大恒科技大厦五层 邮编:100080
Floor 5th,Daheng Building,Zhongguancun,Beijing,China,100080
51Aspx.com 版权所有 CopyRight © 2006-2022. 京ICP备09089570号 | 京公网安备11010702000869号