mirror of
https://gitee.com/fastadminnet/framework.git
synced 2026-07-06 23:02:48 +08:00
改进多对多写入
This commit is contained in:
@@ -439,11 +439,11 @@ class Relation
|
|||||||
/**
|
/**
|
||||||
* 保存当前关联数据对象
|
* 保存当前关联数据对象
|
||||||
* @access public
|
* @access public
|
||||||
* @param array $data 数据
|
* @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键
|
||||||
* @param array $pivot 中间表额外数据
|
* @param array $pivot 中间表额外数据
|
||||||
* @return integer
|
* @return integer
|
||||||
*/
|
*/
|
||||||
public function save(array $data, array $pivot = [])
|
public function save($data, array $pivot = [])
|
||||||
{
|
{
|
||||||
// 判断关联类型
|
// 判断关联类型
|
||||||
switch ($this->type) {
|
switch ($this->type) {
|
||||||
@@ -454,18 +454,30 @@ class Relation
|
|||||||
$model = new $this->model;
|
$model = new $this->model;
|
||||||
return $model->save($data);
|
return $model->save($data);
|
||||||
case self::BELONGS_TO_MANY:
|
case self::BELONGS_TO_MANY:
|
||||||
// 保存关联表数据
|
if (is_array($data)) {
|
||||||
$model = new $this->model;
|
// 保存关联表数据
|
||||||
$result = $model->save($data);
|
$model = new $this->model;
|
||||||
if ($result) {
|
$model->save($data);
|
||||||
|
$relationFk = $model->getPk();
|
||||||
|
$id = $model->$relationFk;
|
||||||
|
} elseif (is_int($data)) {
|
||||||
|
// 根据关联表主键直接写入中间表
|
||||||
|
$id = $data;
|
||||||
|
} elseif ($data instanceof Model) {
|
||||||
|
// 根据关联表主键直接写入中间表
|
||||||
|
$relationFk = $data->getPk();
|
||||||
|
$id = $data->$relationFk;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($id) {
|
||||||
// 保存中间表数据
|
// 保存中间表数据
|
||||||
$pk = $this->parent->getPk();
|
$pk = $this->parent->getPk();
|
||||||
$relationFk = $model->getPk();
|
|
||||||
$pivot[$this->localKey] = $this->parent->$pk;
|
$pivot[$this->localKey] = $this->parent->$pk;
|
||||||
$pivot[$this->foreignKey] = $model->$relationFk;
|
$pivot[$this->foreignKey] = $id;
|
||||||
$result = Db::table($this->middle)->insert($pivot);
|
return Db::table($this->middle)->insert($pivot);
|
||||||
|
} else {
|
||||||
|
throw new Exception(' relation data write error');
|
||||||
}
|
}
|
||||||
return $result;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user