normykinz's avatar

Many to Many Relationship Confusion.

I've been using Laravel since v5 but for some odd reason Eloquent relationships make my brain turn to mush. Help me out here peeps.

I have groups and users. A group can have many users and a user can have many groups. To help me out I created a pivot model defined like this ...

<?php

namespace App\Models;

use App\Enums\Group\GroupUserRole;
use Illuminate\Database\Eloquent\Relations\Pivot;

class GroupUser extends Pivot
{
    protected $fillable = [
        'group_id',
        'user_id',
        'role',
    ];

    protected $casts = [
        'role' => GroupUserRole::class,
    ];
}

With a pivot table migration defined as ...

Schema::create('group_user', function (Blueprint $table) {
    $table->uuid('group_id');
    $table->uuid('user_id');
    $table->string('role')->default(GroupUserRole::MEMBER);
    $table->timestamps();

    $table->unique(['group_id', 'user_id']);
});

User model has a belongsTo definded as ...

public function groups(): BelongsToMany
{
    return $this->belongsToMany(Group::class);
}

And the group model has the inverse defined ...

public function users(): BelongsToMany
{
    return $this->belongsToMany(User::class);
}

I have an action defined to create a group owner ...

<?php

namespace App\Actions\Group;

use App\Enums\Group\GroupUserRole;
use App\Models\Group;
use App\Models\GroupUser;
use App\Models\User;

class CreateGroupOwner
{
    public function create(Group $group, User $user): GroupUser
    {
        return GroupUser::create([
            'group_id' => $group->id,
            'user_id' => $user->id,
            'role' => GroupUserRole::OWNER,
        ]);
    }
}

But when testing the action in a feature test (using Pest) I get this strange error ...

Tests\Feature\Group\CreateGroupFormTest > it makes the authenticated user the new group's owner                                                       QueryException
  SQLSTATE[HY000]: General error: 1 no such table: group_users (Connection: sqlite, SQL: select count(*) as aggregate from "group_users" where ("user_id" = 9bc00794-27f1-4a3b-a57d-255712efb00e and "group_id" = 9bc00794-35b8-4c00-97d2-0d65b9ac929d and "type" = owner))

Can anybody cast some light on what obvious mistake i'm making here?

0 likes
4 replies
normykinz's avatar

Thanks for the help peeps but I figured it out eventually. I was nothing to do with the production code. I was my test that was going boo!

$expected = [
        'user_id' => $user->id,
        'group_id' => $group->id,
        'role' => GroupUserRole::OWNER->value,
    ];

    expect($expected)->toBeInDatabase('group_users');

Of courde the table name was wrong in the expecation.

amitsolanki24_'s avatar

Basically it's saying your database don't have group_users table try to run migrate command.

php artisan migrate:fresh
``

Please or to participate in this conversation.