Is it possible for a pivot table to have a many-to-many relationship with yet another table?

  database, eloquent, laravel

Let’s say there is a tasks table, and a user table. A task can have many users assigned through the user_task pivot table, which has a field is_done which tells if an assigned user has done the task. So far so good.

Now let’s say there is also a subtasks table, and each task can have multiple subtasks.

Now if we also want to save for each assigned user which subtasks they are assigned to, for example in a user_task_subtask table.

So all tables would like like this:

user: [id, name]
task: [id, title]
subtask: [id, title, task_id]
user_task: [id, user_id, task_id, is_done]
user_task_subtask: [user_task_id, subtask_id]

Using eloquent, I assume I could type something like $task->users()->where('user_id', 1)->pivot->subtasks to access all the subtasks of user 1 for this particular task. I tried this:

class Task extends Model
    public function users()
        return $this

and then add an extra relationship on the pivot:

class UserTaskDetails extends Pivot
    public function subtasks()
         $this->belongsToMany(Subtask::class, 'user_task_subtask', ...); // <-- what to write here exactly?

But I cannot get this subtasks relationship to work properly. Can anyone help me out?

Source: Laravel

Leave a Reply