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仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题