Skip to content

Commit 1411abe

Browse files
author
Peyman Aslani
committed
Fix BelongsToMany relation to support objectId and array values
1 parent 153af6c commit 1411abe

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/Relations/BelongsToMany.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,12 @@ public function attach($id, array $attributes = [], $touch = true)
208208

209209
// Attach the new ids to the parent model.
210210
if (\MongoDB\Laravel\Eloquent\Model::isDocumentModel($this->parent)) {
211-
$this->parent->push($this->relatedPivotKey, (array) $id, true);
211+
if ($id instanceof \MongoDB\BSON\ObjectId) {
212+
$id = [$id];
213+
} else {
214+
$id = (array) $id;
215+
}
216+
$this->parent->push($this->relatedPivotKey, $id, true);
212217
} else {
213218
$instance = new $this->related();
214219
$instance->forceFill([$this->relatedKey => $id]);
@@ -275,7 +280,8 @@ protected function buildDictionary(Collection $results)
275280

276281
foreach ($results as $result) {
277282
foreach ($result->$foreign as $item) {
278-
$dictionary[$item][] = $result;
283+
$key = is_object($item) ? (string) $item : $item;
284+
$dictionary[$key][] = $result;
279285
}
280286
}
281287

0 commit comments

Comments
 (0)