0
votes

I would like to solve the following problem:

I have a model (Car) that is loaded as a relation to another model (Driver) with a pivot table.

Car -> belongsToMany Driver (with pivot) -> belongsToMany Accessoires (with Pivot).

The model in turn has relations (accessories) that are loaded with pivot.

The problem: The model Accessories has two pivot tables which can be loaded depending on other factors. If the model Accessories is loaded as a relation of Driver as a relation of Car, the pivot tables should be output correctly.

This is what it looks like at the moment:

 collect($request->input('data.driver'))->each(function ($driver) use
        (
            $car
        ) {

            $ndriver = Driver::findOrFail($driver['id']);

            $added = $car->driver()->save($driver, [
                'custom' => $driver['custom'],
                'title' => $driver['title'],
                'factor' => $driver['factor'],
            ]);

            /*Save attributes*/
            $added->syncDriverAttributes($driver['attributes']],
                $car->id);
        });

Now I should actually specify in $added->syncDriverAttributes($driver['attributes'], $car->id); the pivot ID of the created pivot data in $added. Unfortunately I can't find out what the pivot ID is at the moment, because it is not returned in $added.

The problem: I can't find out the last pivot ID from the timestamp either, because all entries have the same timestamp.

So my question is: How can I solve that?

1
A pivot table usually does not have an id column. The primary key is a composite of the two model keys being linked. So accessories_drivers would have accessory_id and driver_id as a composite primary key.Aken Roberts
Okay, I understand that. I added a bigIncrements to accessories_drivers hoping that I could get a return. How else can I solve that issue to link the pivot to a specific car, driver and accessory? Maybe I could generate a UUID and save this as pivot` for $car->driver() and reference that as foreign key in the pivot for a accessory?SPQRInc

1 Answers

0
votes

You can of course do it but you should use withPivot method when defining your relationship to tell what additional fields you want to have:

public function driver()
{
   return $this->belongsToMany(Driver::class)->withPivot(['id']);
}