From ca228203c91910aff3f44409db1b79a013355a5a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 Jan 2017 16:50:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E5=A4=9A=E5=AF=B9=E5=A4=9A?= =?UTF-8?q?=E7=9A=84attach=E6=96=B9=E6=B3=95=E7=9A=84=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/relation/BelongsToMany.php | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/library/think/model/relation/BelongsToMany.php b/library/think/model/relation/BelongsToMany.php index c85a8c0c..128287e0 100644 --- a/library/think/model/relation/BelongsToMany.php +++ b/library/think/model/relation/BelongsToMany.php @@ -54,7 +54,7 @@ class BelongsToMany extends Relation $localKey = $this->localKey; $middle = $this->middle; if ($closure) { - call_user_func_array($closure, [& $this->query]); + call_user_func_array($closure, [ & $this->query]); } // 关联查询 $pk = $this->parent->getPk(); @@ -174,8 +174,8 @@ class BelongsToMany extends Relation return $this->belongsToManyQuery($this->middle, $this->foreignKey, $this->localKey, [ 'pivot.' . $this->localKey => [ 'exp', - '=' . $this->parent->getTable() . '.' . $this->parent->getPk() - ] + '=' . $this->parent->getTable() . '.' . $this->parent->getPk(), + ], ])->fetchSql()->count(); } @@ -271,7 +271,7 @@ class BelongsToMany extends Relation * @access public * @param mixed $data 数据 可以使用数组、关联模型对象 或者 关联对象的主键 * @param array $pivot 中间表额外数据 - * @return int + * @return array|Pivot * @throws Exception */ public function attach($data, $pivot = []) @@ -301,7 +301,12 @@ class BelongsToMany extends Relation $ids = (array) $id; foreach ($ids as $id) { $pivot[$this->foreignKey] = $id; - $result = $this->query->table($this->middle)->insert($pivot, true); + $this->query->table($this->middle)->insert($pivot, true); + $result[] = new Pivot($pivot, $this->middle); + } + if (count($result) == 1) { + // 返回中间表模型对象 + $result = $result[0]; } return $result; } else {