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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘