'laravel morphToMany with additional field in pivot table

I create the following database structure to manage different service contents for different batch and just because this structure must be replicated for sub services too I decided to use a "Many To Many Polymorphic Relations" with Laravel.

img database structure.

To create a new record in table "service_and_relatives_contents" and another association record in table "service____relative_content_batch_a" (my pivot table) I used :

$service -> relatives() -> create($arrRelatives)

the problem is with that code is that I can't populate "batches_id" fields in my pivot table. For this reason I used the following code :

$relativeId = $service->relatives()->create($arrRelatives)->id;
$service->relatives()->updateExistingPivot($relativeId,['batches_id'=>$keyRelatives]);

It works well but it is the right way to create and associate a record in the same time?

Please consider this as an example, I will use laravel conventions for table name and foreign-key for the live version.



Solution 1:[1]

I tink make a create query build morpth and polymorph Many to Many

               |-----------------------------------------|
User::join(table_a, user.id, forein.id)->join(table_b, table_a.id, forein.id)
  |----------------------|

> $res = User::join('model_has_roles','users.id','model_id')->join('role_has_permissions','model_has_roles.role_id','model_id')->get()

thank

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1