设置中间表模型更新条件

This commit is contained in:
yunwuxin
2018-05-07 18:22:23 +08:00
parent fa413f48e0
commit de81a830d0

View File

@@ -70,6 +70,19 @@ class BelongsToMany extends Relation
return $this; return $this;
} }
/**
* 获取中间表更新条件
* @param $data
* @return array
*/
protected function getUpdateWhere($data)
{
return [
$this->localKey => $data[$this->localKey],
$this->foreignKey => $data[$this->foreignKey]
];
}
/** /**
* 实例化中间表模型 * 实例化中间表模型
* @param $data * @param $data
@@ -104,7 +117,7 @@ class BelongsToMany extends Relation
} }
} }
} }
$model->setRelation('pivot', $this->newPivot($pivot)); $model->setRelation('pivot', $this->newPivot($pivot)->isUpdate(true, $this->getUpdateWhere($pivot)));
} }
} }
@@ -370,7 +383,7 @@ class BelongsToMany extends Relation
} }
} }
} }
$set->setRelation('pivot', $this->newPivot($pivot)); $set->setRelation('pivot', $this->newPivot($pivot)->isUpdate(true, $this->getUpdateWhere($pivot)));
$data[$pivot[$this->localKey]][] = $set; $data[$pivot[$this->localKey]][] = $set;
} }
return $data; return $data;
@@ -473,7 +486,7 @@ class BelongsToMany extends Relation
foreach ($ids as $id) { foreach ($ids as $id) {
$pivot[$this->foreignKey] = $id; $pivot[$this->foreignKey] = $id;
$this->pivot->insert($pivot, true); $this->pivot->insert($pivot, true);
$result[] = $this->newPivot($pivot); $result[] = $this->newPivot($pivot)->isUpdate(true, $this->getUpdateWhere($pivot));
} }
if (count($result) == 1) { if (count($result) == 1) {
// 返回中间表模型对象 // 返回中间表模型对象