2017-07-01 119 views
0

我有以下3种型号:Laravel 5.2 - 一对多或多对多关系?

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张桌子之间有什么样的关系 - 这是一对多还是多对多的关系?

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

回答

0

你有这样的事情

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/

希望它对你也有帮助。