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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题