简体   繁体   English

Laravel 9 Nova 4 与自定义 Pivot 的关系表和字段名称

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

I am trying to sort out some relationship with nova v4, but it's not working.我正在尝试理清与 nova v4 的一些关系,但它不起作用。 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??那么为什么 nova 正在搜索 a_users_groups 呢?

I have searched nova documentation but nothing is specified there for a custom pivot table name我搜索了 nova 文档,但没有为自定义 pivot 表名指定任何内容

AUser is my model to represent my apps users. AUser 是我的 model 代表我的应用程序用户。 Its not the same users table for the nova admin panel.它与 nova 管理面板的用户表不同。 I am trying to deploy laravel nova on top of already created app.我正在尝试在已创建的应用程序之上部署 laravel nova。 hence I have a pivot table names groups_users which I cannot change.因此我有一个 pivot 表名 groups_users 我无法更改。 I am sure nova allows to supply custom pivot table names with foreign keys?我确定 nova 允许提供带有外键的自定义 pivot 表名?

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.实际上,可以在模型中定义关系,就像 laravel 9 文档中提到的那样。 We do not need to use the ->withPivot here我们不需要在这里使用 ->withPivot

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM