du20150401 2018-07-10 16:03
浏览 38
已采纳

在laravel 5.6中创建层次关系

I'm pretty new to laravel and trying to create my first app.
I have three different classes: User, Activity and Lecture.
Users are capable of creating an activity and lecture.
Every activity has its technical manager, product manager and activity manager, and users are capable of enrolling the activities.
Every lecture has its lecturer and users are capable of enrolling the lecture.
I want to create the eloquent relationships necessary but I'm not sure if the users should belong to the activity or vice versa. I have accomplished one of my goals (creating a relationship between users and activity managers) however, I'm confused with the rest of it and feel like it is not the best way to achieve my results.
In that moment, my code looks like that:

App\Activity :

class Activity extends Model
{

    protected $guarded = [];

    public function TechnicalManager(){
        return $this->belongsTo('App\User','technical_manager');
    }

    public function ActivityManager(){
        return $this->belongsTo('App\User','activity_manager');
    }

    public function ProductManager(){
        return $this->belongsTo('App\User','product_manager');
    }

    public function Enrollers(){
        return $this->belongsToMany('App\User','user_activity');
    }
}

App\User :

class User extends Authenticatable
{
    use Notifiable;

    public function activities(){
        return $this->belongsToMany('App\Activity','id');
    }
}
  • 写回答

1条回答 默认 最新

  • du4373 2018-07-10 16:10
    关注

    If you plan on using Eloquent's relationships, then the idea would be:

    1. Do I need to access users (Enrollers) from Activity and call it by accessing the relationship? If yes, write the relationship

    I see nothing wrong with writing relationships on both sides of a model, as long as you use them. If you're not going to use them, then why have them?

    Image the situation:

    Find a user, it's activities and who is the technical manager and the activity manager for the activities

    User::with(['activities','activities.TechnicalManager','activities.ActivityManager'])->find($id)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?