titonior
titonior

Reputation: 167

L5.5 relationship of pivot table with another model

In my application, a model Device has a many-to-many relationship with model Task. A combination of Device and Task could be assigned to a various number of model User. example: Device A has a Task Check something and this should be done by User Frank and Steven.

From my point of view, this should be a "standard problem", but so far I could not find a proper solution.

Right now, I use following workaround: a) added an unique ID id to the device_task pivot table b) query id from the pivot table c) create a new table device_task_user which contains user_id and device_task_id b) use query builder to get/add users

But I am really not happy with this approche.

Would it be possible, that the pivot table also extends Model and then have a one-to-many relationship with User? Or would you suggest to add a json colum to the pivot table and store the users there?

Any idea would be very welcome!

Upvotes: 1

Views: 299

Answers (2)

Mahdi Younesi
Mahdi Younesi

Reputation: 7509

Modify many-to-many relationship to hold an extra field user_id

class Device extends Model
{

  public function tasks()
  {
    return $this->belongsToMany(
        Task::class,
        'device_task',
        'device_id',
        'task_id'
    )->withPivot('user_id');
  }

}

And when updating do like this in controller

$device->tasks()->attach([$taskId]=>['user_id']=>$userId);

And of-course you need DeviceTask model and also a has-many relationship between User model and DeviceTask model to get user's task

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

Would it be possible, that the pivot table also extends Model

Yes, it's possible. From the docs:

If you would like to define a custom model to represent the intermediate table of your relationship, you may call the using method when defining the relationship. All custom models used to represent intermediate tables of relationships must extend the Illuminate\Database\Eloquent\Relations\Pivot class

You also can create a new hasMany() and belongsTo() relationships between Task and Device models and use them as well as existing belongsToMany relationship. And you'll need to define a new relationship between pivot model and User model to be able to get data by device, task or user.

Upvotes: 2

Related Questions