Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add test for BelongsToMany relation with array foreign keys
  • Loading branch information
Peyman Aslani committed Mar 6, 2025
commit 176d8541c609af1c0b59ace22ddd64d376e56d18
6 changes: 6 additions & 0 deletions tests/Models/Role.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use MongoDB\Laravel\Eloquent\DocumentModel;
use MongoDB\Laravel\Relations\BelongsToMany;

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

public function users(): BelongsToMany
{
return $this->belongsToMany(User::class, null, 'role_id', 'user_id');
}

public function sqlUser(): BelongsTo
{
return $this->belongsTo(SqlUser::class);
Expand Down
6 changes: 6 additions & 0 deletions tests/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use MongoDB\Laravel\Eloquent\Builder;
use MongoDB\Laravel\Eloquent\DocumentModel;
use MongoDB\Laravel\Eloquent\MassPrunable;
use MongoDB\Laravel\Relations\BelongsToMany;

/**
* @property string $id
Expand Down Expand Up @@ -87,6 +88,11 @@ public function role()
return $this->hasOne(Role::class);
}

public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class, null, 'user_id', 'role_id');
}

public function sqlRole()
{
return $this->hasOne(SqlRole::class);
Expand Down
16 changes: 16 additions & 0 deletions tests/RelationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,22 @@ public function testBelongsToManyAttachArray(): void
$this->assertCount(2, $user->clients);
}

public function testBelongsToManyRelationSupportsArrayForeignKeys(): void
{
$user = User::create(['name' => 'John Doe']);
$role1 = Role::create(['name' => 'Admin']);
$role2 = Role::create(['name' => 'Editor']);

$user->roles()->attach([$role1->id, $role2->id]);

$retrievedUser = User::with('roles')->find($user->id);
$this->assertCount(2, $retrievedUser->roles);
$this->assertEqualsCanonicalizing(
[$role1->id, $role2->id],
$retrievedUser->roles->pluck('id')->toArray()
);
}

public function testBelongsToManyAttachEloquentCollection(): void
{
User::create(['name' => 'John Doe']);
Expand Down