简体   繁体   中英

Laravel many-to-many relationship on the same model

I have a model Job .

A Job can require other Jobs be completed before it can begin.

A Job may be the pre-required job for many Jobs at once.

So, say Job A depends on Job B and Job C , I would like to be able to call job->requiredJobs and get those two jobs.

As it stands, I have the following:

class Job extends Model
{

    public function requiredJobs() 
    {
        return $this->hasMany('App\Job', 'required_job_id');
    }
}

However, I'm finding that if I create a Job D and have it require Job B and Job C , it overrides Job A 's required jobs field, since it seems to be adding required_job_id onto the required jobs, instead of creating an array on the dependent job.

Hope this all makes sense! I'm not entirely sure if I need two definitions, or if hasMany is the wrong relationship ( belongsToMany instead?...)

Nick 's answer pushed me in the right direction.

Here is how I ended up defining my model:

class Job extends Model
{

    public function requiredJobs() 
    {
        return $this->belongsToMany('App\Job', null, 'dependent_job_ids', 'required_job_ids');
    }

    public function dependentJobs() 
    {
        return $this->belongsToMany('App\Job', null, 'required_job_ids', 'dependent_job_ids');
    }
}

This meant that when I call dependentJob->requiredJobs()->save(requiredJob) , a couple things happen:

  1. dependentJob gets an array of IDs required_job_ids , and I can call dependentJob->requiredJobs to get the entire list of job models.
  2. requiredJob gets an array of IDs dependent_job_ids , and I can call requiredJob->dependentJobs to get the entire list of job models.

Works like a charm!

对于多对多关系belongsToMany()是正确的方法,但您还需要一个数据透视表来存储链接。

This is just to add on anyone looking for a solution on the same issue, relating the same model.

Here you can create a joining table with normal Many to Many Relationships and attach ids as normal Laravel relationships

public function requiredJobs()
{
    return $this->belongsToMany('App\Job','dependent_jobs_required_jobs','dependent_job_ids','required_job_ids');
}

public function dependentJobs()
{
    return $this->belongsToMany('App\Job','dependent_jobs_required_jobs','required_job_ids','dependent_job_ids');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM