改进多对多的pivot对象

This commit is contained in:
thinkphp
2017-12-13 17:12:51 +08:00
parent e3320cd3f6
commit 924d78d5f7

View File

@@ -52,6 +52,10 @@ class BelongsToMany extends Relation
} }
$this->query = (new $model)->db(); $this->query = (new $model)->db();
$this->pivot = $this->newPivot(); $this->pivot = $this->newPivot();
if (!is_subclass_of($this->pivot, '\\think\\model\\Pivot')) {
$this->pivot->name($this->middle);
}
} }
/** /**
@@ -383,7 +387,7 @@ class BelongsToMany extends Relation
{ {
// 关联查询封装 // 关联查询封装
$tableName = $this->query->getTable(); $tableName = $this->query->getTable();
$table = $this->pivot->getTable($this->middle); $table = $this->pivot->getTable();
$fields = $this->getQueryFields($tableName); $fields = $this->getQueryFields($tableName);
$query = $this->query->field($fields) $query = $this->query->field($fields)
@@ -467,7 +471,7 @@ class BelongsToMany extends Relation
$ids = (array) $id; $ids = (array) $id;
foreach ($ids as $id) { foreach ($ids as $id) {
$pivot[$this->foreignKey] = $id; $pivot[$this->foreignKey] = $id;
$this->pivot->name($this->middle)->insert($pivot, true); $this->pivot->insert($pivot, true);
$result[] = $this->newPivot($pivot); $result[] = $this->newPivot($pivot);
} }
if (count($result) == 1) { if (count($result) == 1) {
@@ -505,7 +509,7 @@ class BelongsToMany extends Relation
if (isset($id)) { if (isset($id)) {
$pivot[$this->foreignKey] = is_array($id) ? ['in', $id] : $id; $pivot[$this->foreignKey] = is_array($id) ? ['in', $id] : $id;
} }
$this->pivot->name($this->middle)->where($pivot)->delete(); $this->pivot->where($pivot)->delete();
// 删除关联表数据 // 删除关联表数据
if (isset($id) && $relationDel) { if (isset($id) && $relationDel) {
$model = $this->model; $model = $this->model;
@@ -527,7 +531,7 @@ class BelongsToMany extends Relation
'updated' => [], 'updated' => [],
]; ];
$pk = $this->parent->getPk(); $pk = $this->parent->getPk();
$current = $this->pivot->name($this->middle)->where($this->localKey, $this->parent->$pk) $current = $this->pivot->where($this->localKey, $this->parent->$pk)
->column($this->foreignKey); ->column($this->foreignKey);
$records = []; $records = [];
@@ -571,7 +575,7 @@ class BelongsToMany extends Relation
{ {
if (empty($this->baseQuery) && $this->parent->getData()) { if (empty($this->baseQuery) && $this->parent->getData()) {
$pk = $this->parent->getPk(); $pk = $this->parent->getPk();
$table = $this->pivot->getTable($this->middle); $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->query->join($table . ' pivot', 'pivot.' . $this->foreignKey . '=' . $this->query->getTable() . '.' . $this->query->getPk())->where('pivot.' . $this->localKey, $this->parent->$pk);
$this->baseQuery = true; $this->baseQuery = true;
} }