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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?