我有以下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');
});
求职者可以将多个职位添加到候选名单中。这三个表之间的关系是什么类型 - 是一对多还是多对多?
应该在所有三种模型中定义的正确关系是什么?
答案 0 :(得分:0)
你有类似的东西
Jobs
- Job ID
- Else
JobsJobShortListsPivot
- Job ID
- Shortlist ID
- Else
JobShortLists
- ShortList ID
- JobSeeker ID
- Else
JobSeekers
- JobSeeker ID
- Else
在JobSeekers模型上:
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/
希望它对你也有帮助。