From c2fff2b45d777a2cef2940b2989f1362f4206c81 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 22 Dec 2016 18:06:01 +0800 Subject: [PATCH] =?UTF-8?q?BelongsToMany=E7=B1=BB=E7=9A=84attach=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=94=B9=E8=BF=9B=20=E6=94=AF=E6=8C=81=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../think/model/relation/BelongsToMany.php | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/library/think/model/relation/BelongsToMany.php b/library/think/model/relation/BelongsToMany.php index a07de2d7..53f344a6 100644 --- a/library/think/model/relation/BelongsToMany.php +++ b/library/think/model/relation/BelongsToMany.php @@ -252,10 +252,14 @@ class BelongsToMany extends Relation public function attach($data, $pivot = []) { if (is_array($data)) { - // 保存关联表数据 - $model = new $this->model; - $model->save($data); - $id = $model->getLastInsID(); + 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; @@ -267,10 +271,14 @@ class BelongsToMany extends Relation if ($id) { // 保存中间表数据 - $pk = $this->parent->getPk(); - $pivot[$this->localKey] = $this->parent->$pk; - $pivot[$this->foreignKey] = $id; - return $this->query->table($this->middle)->insert($pivot, true); + $pk = $this->parent->getPk(); + $pivot[$this->localKey] = $this->parent->$pk; + $ids = (array) $id; + foreach ($ids as $id) { + $pivot[$this->foreignKey] = $id; + $result = $this->query->table($this->middle)->insert($pivot, true); + } + return $result; } else { throw new Exception('miss relation data'); }