我有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中有一个belongsToMany
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
答案 0 :(得分:0)
UserModel中的belongsToMany函数应该像这样定义:
public function roles() {
return $this->belongsToMany('App\RoleModel',
'User_role_pivot',
'user_serno',
'role_serno');
为了提及关联的密钥,首先提及当前模型的(UserModel)密钥,然后提及其他模型的(RoleModel)密钥。您在两者中使用相同的密钥。