【问题标题】:Laravel 5.2 - One to Many or Many to Many Relationship?Laravel 5.2 - 一对多或多对多关系?
【发布时间】:2017-07-12 03:57:20
【问题描述】:

我有以下 3 个模型:

 class Job extends Model {

     public function jobShortlists()
     {
        return $this->hasMany('App\JobShortlist');
     }
 }

 class Jobseeker extends Model {

     public function jobShortlists()
     {
        return $this->hasMany('App\JobShortlist');
     }
 }

 class JobShortlist extends Model {

     public function jobseeker()
     {
        return $this->belongsTo('App\Jobseeker');
     }

     public function job()
     {
        return $this->belongsTo('App\Job');
     }
 }

还有迁移:

 Schema::create('jobs', function(Blueprint $table)
 {
        $table->increments('id');
        $table->string('job_title', 100);
        ...
 });

 Schema::create('jobseekers', function(Blueprint $table)
 {
        $table->increments('id');
        $table->string('name', 100);
        ...
 });

 Schema::create('job_shortlists', function(Blueprint $table)
 {
        $table->increments('id');
        $table->integer('jobseeker_id')->unsigned();
        $table->integer('job_id')->unsigned()->unique();

        $table->unique( array('jobseeker_id', 'job_id'));

        $table->foreign('jobseeker_id')
            ->references('id')
            ->on('jobseekers')
            ->onDelete('cascade');

        $table->foreign('job_id')
            ->references('id')
            ->on('jobs')
            ->onDelete('cascade');
 });

求职者可以将多个职位添加到候选名单中。这 3 个表之间是什么类型的关系 - 是一对多还是多对多?

应该在所有三个模型中定义的正确关系是什么?

【问题讨论】:

    标签: laravel-5.2 entity-relationship laravel-eloquent


    【解决方案1】:

    你有这样的东西

     Jobs 
        - Job ID
        - Else
    
     JobsJobShortListsPivot
        - Job ID
        - Shortlist ID
        - Else
    
     JobShortLists
        - ShortList ID
        - JobSeeker ID
        - Else
    
      JobSeekers
        - JobSeeker ID
        - Else
    

    关于求职者模型:

     function shortlists(){
         return $this->hasMany("\App\JobShortLists");
     }
    

    关于 JobShortLists 模型:

     function jobs(){
         return $this->belongsToMany("\App\Jobs", "JobsJobShortLists", 
              "Shortlist ID", "Job ID");
     }
    

    我以前就是这样用过,也成功过,我的第一个学习来源是:

    http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

    希望对你也有帮助。

    【讨论】:

      猜你喜欢
      • 2018-06-15
      • 2016-09-27
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2018-03-16
      • 2021-04-01
      • 2016-12-20
      相关资源
      最近更新 更多