Search code examples
phplaravelmany-to-manyrelationship

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?...)


Solution

  • 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!