dongqiya9552 2016-01-13 17:53
浏览 137
已采纳

三种口才雄辩的关系

The project that I am working on requires a sort of sharing functionality meaning that when a person creates an exercise they can choose to share that exercise with another person and append a certain permission to that exercise (i.e read, write, or execute).

I have three tables(all of which have models): users, exercises, and permissions. In the middle I have an exercise_permission_user table that only has three columns: exercise_id, permission_id, and user_id all of which are foreign keys that point back to their respective tables.

The problem comes with establishing a three way many to many relationship among these tables in Laravel 5. More specifically, when a person shares an exercise, I need to input the id's of the exercise being shared, the user it is being shared with, and the permission that is being appended into the exercise_permission_user table. I then need to be able to query the user_id of this table and see all exercises that are being shared with a certain user. If the user Mike has an ID of 3, then I would like to query the middle table for that ID and find the exercise he has access to as well as the permission that he is being granted.

I am still in the learning process when it comes to eloquent so any help would be greatly appreciated. I am not necessarily looking for someone to build this for me, just some help that will give me the information necessary to do it on my own. Thanks to all that help!

  • 写回答

1条回答 默认 最新

  • dskpywvki951583595 2016-01-13 23:01
    关注

    I've struggled with this issue a couple of times. As far as I could research, I didn't find a Laravel native way of coding this kind of three way many to many relationship. What I generally do is to create a model for the pivot table. So, a SharedExercise model (or the name you want to use) with a protected $table property set as 'exercises_permission_user'. Inside that model you set the relationships with user, exercises and permissions. Then, you can write:

    $sharedExercises = SharedExercise::where('user_id', $userId)->get();
    

    Pay attention to the table and model naming. I usually name tables using laravel's conventions, but when I have this 3 way many to many, I try to find a more describing name than the convention. So, for example instead of exercises_permission_user and ExercisePermissionUser model, maybe shared_exercises and SharedExercise names are better. Note that this isn't THE way to do it. It's how I do it as a result of not finding a convention in the documentation.

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

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算