Laravel 9 Nova 4 Relationship with custom Pivot Table and field names

Viewed 14

I am trying to sort out some relationship with nova v4, but it's not working. I have :

users
id
name

groups
id
name

groups_users
user_id
group_id

now I want to show groups belonging to users inside user view

and same for users

but this is not working for me

public function user(){
        return $this->belongsToMany(AUsers::class)
        ->withPivot('groups_users', 'group_id', 'user_id');
}

I receive this error:

error: "message": "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel-api.a_users_groups' doesn't exist.



a_users_groups doesn't exist because my pivot table is "groups_users"

so why nova is searching for a_users_groups ??

I have searched nova documentation but nothing is specified there for a custom pivot table name

AUser is my model to represent my apps users. Its not the same users table for the nova admin panel. I am trying to deploy laravel nova on top of already created app. hence I have a pivot table names groups_users which I cannot change. I am sure nova allows to supply custom pivot table names with foreign keys?

1 Answers

I have found the answer to my question:

Actually relationships could be defined in the models exactly like it is mentioned in laravel 9 documentation. We do not need to use the ->withPivot here

public function user(){
    return $this->belongsToMany(AUsers::class, 'groups_users', 'group_id', 'user_id');
}
Related