php - 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_Groups
或 AD_UserXAD_Group
解决方案
因为你有一个“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')
}
推荐阅读
- docker - Traefik - 转发到外部 IP
- download - AppleScript - 复制文件夹内容显示错误 - 下载和解压缩作品
- javascript - 如何使用 React Router Redirect 在功能组件之间传递状态?
- raspberry-pi - 如何从 Raspbian 的命令行更改音频输出设备?
- c# - 通过 ref 传递引用类型
- python - Python 和 Pygame 循环不递增
- python - 如何从 Python 编程中的输入代码中删除空格(多个空格、制表符、下一行)?
- sql - WHERE NOT price =(从产品中选择价格)不起作用。(SQL)
- apache-spark - 初始化 SparkContext 后是否可以更改 SparkContext.sparkUser()?
- javascript - 如何滚动在 onClick 事件之前隐藏的“onClick”组件