首页 > 解决方案 > Lumen - Eloquent:覆盖连接表的名称

问题描述

我正在为一个软件构建一个数据库,其中身份验证与公司的 LDAP 服务器相结合。我现在有两张桌子

AD_Groups

AD_Users

哪些在表中加入

AD_UsersXAD_Groups

我已经学会了如何用雄辩的语言建立关系。官方文档中举例说明了多对多关系: https ://laravel.com/docs/5.8/eloquent-relationships#many-to-many

现在,如您所见,eloquent 的以下功能对我没有多大帮助:

"To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns."

因此,我需要使用第二个参数来覆盖这个派生名称,如下所述:

"As mentioned previously, to determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method:

return $this->belongsToMany('App\Role', 'role_user');

但是从上面的文档示例中可以看出,臭名昭著的“蛇案”仍然适用于名称。但是,我担心这可能不适用于我的情况。诚然,AD_UsersXAD_Groups它非常丑陋,我担心 eloquent/lumen 将无法正确识别其元素并正确应用蛇案例规则。但我不确定,因此我问你什么最有可能奏效。使用AD_UsersXAD_GroupsAD_UserXAD_Group

标签: phplaraveleloquentlumen

解决方案


因为你有一个“x”,所以 Eloquent 的魔法永远无法自动匹配你的桌子。

您可以覆盖用户模型中关系中的表名。如果它们不是 Eloquent 预期的“group_id”和“user_id”,您还可以指定键:

function groups() {
    return $this->belongsToMany(GroupModel::class, 'AD_UsersXAD_Groups', 'user_id_key', 'group_id_key')
}

在您的 Group 模型中,您可以这样做来扭转它

function users() {
    return $this->belongsToMany(UserModel::class, 'AD_UsersXAD_Groups', 'group_id_key', 'user_id_key')
}

推荐阅读