Laravel many-to-many relationship on the same model

Viewed 3131

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

3 Answers

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');
}
Related