mirror of
https://gitee.com/fastadminnet/framework.git
synced 2026-07-07 07:12:47 +08:00
BelongsToMany类的attach方法改进 支持批量写入
This commit is contained in:
@@ -252,10 +252,14 @@ class BelongsToMany extends Relation
|
|||||||
public function attach($data, $pivot = [])
|
public function attach($data, $pivot = [])
|
||||||
{
|
{
|
||||||
if (is_array($data)) {
|
if (is_array($data)) {
|
||||||
// 保存关联表数据
|
if (key($data) === 0) {
|
||||||
$model = new $this->model;
|
$id = $data;
|
||||||
$model->save($data);
|
} else {
|
||||||
$id = $model->getLastInsID();
|
// 保存关联表数据
|
||||||
|
$model = new $this->model;
|
||||||
|
$model->save($data);
|
||||||
|
$id = $model->getLastInsID();
|
||||||
|
}
|
||||||
} elseif (is_numeric($data) || is_string($data)) {
|
} elseif (is_numeric($data) || is_string($data)) {
|
||||||
// 根据关联表主键直接写入中间表
|
// 根据关联表主键直接写入中间表
|
||||||
$id = $data;
|
$id = $data;
|
||||||
@@ -267,10 +271,14 @@ class BelongsToMany extends Relation
|
|||||||
|
|
||||||
if ($id) {
|
if ($id) {
|
||||||
// 保存中间表数据
|
// 保存中间表数据
|
||||||
$pk = $this->parent->getPk();
|
$pk = $this->parent->getPk();
|
||||||
$pivot[$this->localKey] = $this->parent->$pk;
|
$pivot[$this->localKey] = $this->parent->$pk;
|
||||||
$pivot[$this->foreignKey] = $id;
|
$ids = (array) $id;
|
||||||
return $this->query->table($this->middle)->insert($pivot, true);
|
foreach ($ids as $id) {
|
||||||
|
$pivot[$this->foreignKey] = $id;
|
||||||
|
$result = $this->query->table($this->middle)->insert($pivot, true);
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
} else {
|
} else {
|
||||||
throw new Exception('miss relation data');
|
throw new Exception('miss relation data');
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user