Skip to content

Commit 176d854

Browse files
author
Peyman Aslani
committed
add test for BelongsToMany relation with array foreign keys
1 parent 1411abe commit 176d854

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

tests/Models/Role.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Illuminate\Database\Eloquent\Model;
88
use Illuminate\Database\Eloquent\Relations\BelongsTo;
99
use MongoDB\Laravel\Eloquent\DocumentModel;
10+
use MongoDB\Laravel\Relations\BelongsToMany;
1011

1112
class Role extends Model
1213
{
@@ -22,6 +23,11 @@ public function user(): BelongsTo
2223
return $this->belongsTo(User::class);
2324
}
2425

26+
public function users(): BelongsToMany
27+
{
28+
return $this->belongsToMany(User::class, null, 'role_id', 'user_id');
29+
}
30+
2531
public function sqlUser(): BelongsTo
2632
{
2733
return $this->belongsTo(SqlUser::class);

tests/Models/User.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use MongoDB\Laravel\Eloquent\Builder;
1818
use MongoDB\Laravel\Eloquent\DocumentModel;
1919
use MongoDB\Laravel\Eloquent\MassPrunable;
20+
use MongoDB\Laravel\Relations\BelongsToMany;
2021

2122
/**
2223
* @property string $id
@@ -87,6 +88,11 @@ public function role()
8788
return $this->hasOne(Role::class);
8889
}
8990

91+
public function roles(): BelongsToMany
92+
{
93+
return $this->belongsToMany(Role::class, null, 'user_id', 'role_id');
94+
}
95+
9096
public function sqlRole()
9197
{
9298
return $this->hasOne(SqlRole::class);

tests/RelationsTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,22 @@ public function testBelongsToManyAttachArray(): void
338338
$this->assertCount(2, $user->clients);
339339
}
340340

341+
public function testBelongsToManyRelationSupportsArrayForeignKeys(): void
342+
{
343+
$user = User::create(['name' => 'John Doe']);
344+
$role1 = Role::create(['name' => 'Admin']);
345+
$role2 = Role::create(['name' => 'Editor']);
346+
347+
$user->roles()->attach([$role1->id, $role2->id]);
348+
349+
$retrievedUser = User::with('roles')->find($user->id);
350+
$this->assertCount(2, $retrievedUser->roles);
351+
$this->assertEqualsCanonicalizing(
352+
[$role1->id, $role2->id],
353+
$retrievedUser->roles->pluck('id')->toArray()
354+
);
355+
}
356+
341357
public function testBelongsToManyAttachEloquentCollection(): void
342358
{
343359
User::create(['name' => 'John Doe']);

0 commit comments

Comments
 (0)