doujiao1981 2013-01-09 21:47
浏览 238
已采纳

我应该如何为Laravel中的多个中间表构建Eloquent ORM模型?

I can't find anywhere the information on how you have several intermediate tables with your Eloquent ORM models. The problem I'm facing is that I have a table for my users, permissions and roles. These are the 4 tables:

Permissions:

id
name

Permission_roles:

id
name

Permission_role_mappings:

id
permission_id
permission_role_id

Permission_role_user_mappings:

id
permission_role_id
user_id

(Well, I also have a users table but the layout of it doesn't matter since the foreign key is in permission_role_user_mapping.)

So the problem is that I want to be able to get the data from the permissions table when calling from the User model. I have some trouble grasping the workflow with Eloquent ORM altogether so if I'm missing something basic which is crucial then please point it out.

According to the documentation it seems that I don't need to create models for the intermediate tables. So how would I specify the relationship from the User class? Could I do something similar to this?

class User extends Eloquent {

    public function permission_role()
    {
        return $this->has_many_and_belongs_to('Permission_Role', 'permission_role_user_mappings');
    }

    public function permission()
    {
        return $this->has_many_and_belongs_to('Permission_Role', 'permission_role_user_mappings')->has_many_and_belongs_to('Permission','permission_role_mappings');
    }
}

This doesn't seem to be working, this is the error:

User::find(1)->first()->permission()->first();
...
Method [permission] is not defined on the Query class.

I also want to be able to get data by starting from Permission_Role and Permission. I'd prefer that the answer would help me specifying all the models required.

  • 写回答

1条回答 默认 最新

  • doulu8847 2013-01-10 19:58
    关注

    Eloquent relationships are accessed as an object property instead of a function.

    User::find(1)->first()->permission;
    

    You can wrap that above statement in the dd function to get a look at it.

    This guide on Eloquent Relationships should be helpful

    Edit for question in comments about selecting all permissions in the role:

    $roles = array();
    $permission_roles = User::find(1)->permission_roles()->get();
    foreach ($permission_roles as $pr) {
      if (! in_array($pr->permissions)) {
        $roles[] = $pr->permissions;
      }
    }
    

    This will get you what you want. However, this will end up doing a lot of queries. It's best to make use of Eager Loading here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?