拉拉威尔多对多关系的转向并不令人惊叹


Laravel Many to many relationship pivot not wowrking

我有3个表

User: user_serno(primary key), username, email

Role: role_serno(primary key), name

User_role_pivot: user_role_privot_serno(primary key), user_serno(foreign key), role_serno(foreign key)

我的UserModel 中有一个BelongToMany

public function roles() {
    return $this->belongsToMany('App'RoleModel', 
        'USER_ROLE_PIVOT', 
        'ROLE_SERNO', 
        'ROLE_SERNO');

我正在尝试获取一个具有角色的用户,但我一直得到空结果,检查查询它不正确。

$user = UserModel::find(121)->roles;

我可以获取用户,但角色不起作用,下面是执行的查询:

第一:select t2.* from ( select rownum AS "rn", t1.* from (select * from USER where USER.USER_SERNO = '121') t1 ) t2 where t2."rn" between 1 and 1

第二:select ROLE.*, USER_ROLE_PIVOT.ROLE_SERNO as pivot_ROLE_SERNO from ROLE inner join USER_ROLE_PIVOT on ROLE.ROLE_SERNO = USER_ROLE_PIVOT.ROLE_SERNO where USER_ROLE_PIVOT.ROLE_SERNO is null

为什么它有ROLE_SERNO为空!我认为应该是USER_SERNO=121

UserModel中的belongToMany函数应该这样定义:

public function roles() {
    return $this->belongsToMany('App'RoleModel', 
        'User_role_pivot', 
        'user_serno',
        'role_serno');

要提及关联的密钥,请首先提及当前模型的(UserModel)密钥,然后提及其他模型的(RoleModel)密钥。您在两者中使用相同的密钥。