123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644 |
- <?php
- namespace think\model\relation;
- use think\Collection;
- use think\Db;
- use think\db\Query;
- use think\Exception;
- use think\Loader;
- use think\Model;
- use think\model\Pivot;
- use think\model\Relation;
- use think\Paginator;
- class BelongsToMany extends Relation
- {
-
- protected $middle;
-
- protected $pivotName;
-
- protected $pivot;
-
- protected $pivotDataName = 'pivot';
-
- public function __construct(Model $parent, $model, $table, $foreignKey, $localKey)
- {
- $this->parent = $parent;
- $this->model = $model;
- $this->foreignKey = $foreignKey;
- $this->localKey = $localKey;
- if (false !== strpos($table, '\\')) {
- $this->pivotName = $table;
- $this->middle = basename(str_replace('\\', '/', $table));
- } else {
- $this->middle = $table;
- }
- $this->query = (new $model)->db();
- $this->pivot = $this->newPivot();
- if ('think\model\Pivot' == get_class($this->pivot)) {
- $this->pivot->name($this->middle);
- }
- }
-
- public function pivot($pivot)
- {
- $this->pivotName = $pivot;
- return $this;
- }
-
- public function pivotDataName($name)
- {
- $this->pivotDataName = $name;
- return $this;
- }
-
- protected function getUpdateWhere($data)
- {
- return [
- $this->localKey => $data[$this->localKey],
- $this->foreignKey => $data[$this->foreignKey],
- ];
- }
-
- protected function newPivot($data = [], $isUpdate = false)
- {
- $class = $this->pivotName ?: '\\think\\model\\Pivot';
- $pivot = new $class($data, $this->parent, $this->middle);
- if ($pivot instanceof Pivot) {
- return $isUpdate ? $pivot->isUpdate(true, $this->getUpdateWhere($data)) : $pivot;
- } else {
- throw new Exception('pivot model must extends: \think\model\Pivot');
- }
- }
-
- protected function hydratePivot($models)
- {
- foreach ($models as $model) {
- $pivot = [];
- foreach ($model->getData() as $key => $val) {
- if (strpos($key, '__')) {
- list($name, $attr) = explode('__', $key, 2);
- if ('pivot' == $name) {
- $pivot[$attr] = $val;
- unset($model->$key);
- }
- }
- }
- $model->setRelation($this->pivotDataName, $this->newPivot($pivot, true));
- }
- }
-
- protected function buildQuery()
- {
- $foreignKey = $this->foreignKey;
- $localKey = $this->localKey;
- $pk = $this->parent->getPk();
-
- $condition['pivot.' . $localKey] = $this->parent->$pk;
- return $this->belongsToManyQuery($foreignKey, $localKey, $condition);
- }
-
- public function getRelation($subRelation = '', $closure = null)
- {
- if ($closure) {
- call_user_func_array($closure, [ & $this->query]);
- }
- $result = $this->buildQuery()->relation($subRelation)->select();
- $this->hydratePivot($result);
- return $result;
- }
-
- public function select($data = null)
- {
- $result = $this->buildQuery()->select($data);
- $this->hydratePivot($result);
- return $result;
- }
-
- public function paginate($listRows = null, $simple = false, $config = [])
- {
- $result = $this->buildQuery()->paginate($listRows, $simple, $config);
- $this->hydratePivot($result);
- return $result;
- }
-
- public function find($data = null)
- {
- $result = $this->buildQuery()->find($data);
- if ($result) {
- $this->hydratePivot([$result]);
- }
- return $result;
- }
-
- public function selectOrFail($data = null)
- {
- return $this->failException(true)->select($data);
- }
-
- public function findOrFail($data = null)
- {
- return $this->failException(true)->find($data);
- }
-
- public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
- {
- return $this->parent;
- }
-
- public function hasWhere($where = [], $fields = null)
- {
- throw new Exception('relation not support: hasWhere');
- }
-
- public function wherePivot($field, $op = null, $condition = null)
- {
- $field = 'pivot.' . $field;
- $this->query->where($field, $op, $condition);
- return $this;
- }
-
- public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure)
- {
- $localKey = $this->localKey;
- $foreignKey = $this->foreignKey;
- $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,
- ],
- ], $relation, $subRelation);
-
- $attr = Loader::parseName($relation);
-
- foreach ($resultSet as $result) {
- if (!isset($data[$result->$pk])) {
- $data[$result->$pk] = [];
- }
- $result->setRelation($attr, $this->resultSetBuild($data[$result->$pk]));
- }
- }
- }
-
- public function eagerlyResult(&$result, $relation, $subRelation, $closure)
- {
- $pk = $result->getPk();
- if (isset($result->$pk)) {
- $pk = $result->$pk;
-
- $data = $this->eagerlyManyToMany(['pivot.' . $this->localKey => $pk], $relation, $subRelation);
-
- if (!isset($data[$pk])) {
- $data[$pk] = [];
- }
- $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$pk]));
- }
- }
-
- public function relationCount($result, $closure)
- {
- $pk = $result->getPk();
- $count = 0;
- if (isset($result->$pk)) {
- $pk = $result->$pk;
- $count = $this->belongsToManyQuery($this->foreignKey, $this->localKey, ['pivot.' . $this->localKey => $pk])->count();
- }
- return $count;
- }
-
- public function getRelationCountQuery($closure, &$name = null)
- {
- if ($closure) {
- $return = call_user_func_array($closure, [ & $this->query]);
- if ($return && is_string($return)) {
- $name = $return;
- }
- }
- return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [
- 'pivot.' . $this->localKey => [
- 'exp',
- Db::raw('=' . $this->parent->getTable() . '.' . $this->parent->getPk()),
- ],
- ])->fetchSql()->count();
- }
-
- protected function eagerlyManyToMany($where, $relation, $subRelation = '')
- {
-
- $list = $this->belongsToManyQuery($this->foreignKey, $this->localKey, $where)->with($subRelation)->select();
-
- $data = [];
- foreach ($list as $set) {
- $pivot = [];
- foreach ($set->getData() as $key => $val) {
- if (strpos($key, '__')) {
- list($name, $attr) = explode('__', $key, 2);
- if ('pivot' == $name) {
- $pivot[$attr] = $val;
- unset($set->$key);
- }
- }
- }
- $set->setRelation($this->pivotDataName, $this->newPivot($pivot, true));
- $data[$pivot[$this->localKey]][] = $set;
- }
- return $data;
- }
-
- protected function belongsToManyQuery($foreignKey, $localKey, $condition = [])
- {
-
- $tableName = $this->query->getTable();
- $table = $this->pivot->getTable();
- $fields = $this->getQueryFields($tableName);
- $query = $this->query->field($fields)
- ->field(true, false, $table, 'pivot', 'pivot__');
- if (empty($this->baseQuery)) {
- $relationFk = $this->query->getPk();
- $query->join([$table => 'pivot'], 'pivot.' . $foreignKey . '=' . $tableName . '.' . $relationFk)
- ->where($condition);
- }
- return $query;
- }
-
- public function save($data, array $pivot = [])
- {
-
- return $this->attach($data, $pivot);
- }
-
- public function saveAll(array $dataSet, array $pivot = [], $samePivot = false)
- {
- $result = false;
- foreach ($dataSet as $key => $data) {
- if (!$samePivot) {
- $pivotData = isset($pivot[$key]) ? $pivot[$key] : [];
- } else {
- $pivotData = $pivot;
- }
- $result = $this->attach($data, $pivotData);
- }
- return $result;
- }
-
- public function attach($data, $pivot = [])
- {
- if (is_array($data)) {
- if (key($data) === 0) {
- $id = $data;
- } else {
-
- $model = new $this->model;
- $model->save($data);
- $id = $model->getLastInsID();
- }
- } elseif (is_numeric($data) || is_string($data)) {
-
- $id = $data;
- } elseif ($data instanceof Model) {
-
- $relationFk = $data->getPk();
- $id = $data->$relationFk;
- }
- if ($id) {
-
- $pk = $this->parent->getPk();
- $pivot[$this->localKey] = $this->parent->$pk;
- $ids = (array) $id;
- foreach ($ids as $id) {
- $pivot[$this->foreignKey] = $id;
- $this->pivot->insert($pivot, true);
- $result[] = $this->newPivot($pivot, true);
- }
- if (count($result) == 1) {
-
- $result = $result[0];
- }
- return $result;
- } else {
- throw new Exception('miss relation data');
- }
- }
-
- public function attached($data)
- {
- if ($data instanceof Model) {
- $relationFk = $data->getPk();
- $id = $data->$relationFk;
- } else {
- $id = $data;
- }
- $pk = $this->parent->getPk();
- $pivot = $this->pivot->where($this->localKey, $this->parent->$pk)->where($this->foreignKey, $id)->find();
- return $pivot ?: false;
- }
-
- public function detach($data = null, $relationDel = false)
- {
- if (is_array($data)) {
- $id = $data;
- } elseif (is_numeric($data) || is_string($data)) {
-
- $id = $data;
- } elseif ($data instanceof Model) {
-
- $relationFk = $data->getPk();
- $id = $data->$relationFk;
- }
-
- $pk = $this->parent->getPk();
- $pivot[$this->localKey] = $this->parent->$pk;
- if (isset($id)) {
- $pivot[$this->foreignKey] = is_array($id) ? ['in', $id] : $id;
- }
- $this->pivot->where($pivot)->delete();
-
- if (isset($id) && $relationDel) {
- $model = $this->model;
- $model::destroy($id);
- }
- }
-
- public function sync($ids, $detaching = true)
- {
- $changes = [
- 'attached' => [],
- 'detached' => [],
- 'updated' => [],
- ];
- $pk = $this->parent->getPk();
- $current = $this->pivot->where($this->localKey, $this->parent->$pk)
- ->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;
- }
-
- protected function baseQuery()
- {
- if (empty($this->baseQuery) && $this->parent->getData()) {
- $pk = $this->parent->getPk();
- $table = $this->pivot->getTable();
- $this->query->join([$table => 'pivot'], 'pivot.' . $this->foreignKey . '=' . $this->query->getTable() . '.' . $this->query->getPk())->where('pivot.' . $this->localKey, $this->parent->$pk);
- $this->baseQuery = true;
- }
- }
- }
|