vendredi 6 septembre 2019

How to use sync in laravel in a pivot table with another foreign key

I have a pivot table and I am using sync when I have to add or remove rows. The problem is that I have a week_day_id that is important when a row must be deleted or added. I need to sync only if both id's and the week_day_id matches.

I alreday tried:

$routine->exercises()->detach($exercisesList);

$routine->exercises()->attach($exercisesList);

and this:

$routine->exercises()->syncWithoutDetaching($exercisesList);

Controller:

public function update(UpdateRoutineRequest $request, Routine $routine) {

// $routine = Routine::where('user_id', Auth::guard('api')->id())->get();

    $this->authorize('update', $routine);
    $routine->name = $request->get('name', $routine->name);
    $routine->description = $request->get('description', $routine->description);

    $exercisesIds = array();


    foreach($request->exercises as $exercise) {
        $arrayTemp = $exercise['exercise_id'];

        array_push($exercisesIds, $arrayTemp);
    }

    $exercisesList = array_combine($exercisesIds, $request->exercises);

    $routine->save();

    $routine->exercises()->syncWithoutDetaching($exercisesList);

    return fractal()
        ->item($routine)
        ->parseIncludes(['user', 'exercises'])
        ->transformWith(new RoutineTransformer)
        ->toArray();
}

tables: https://firebasestorage.googleapis.com/v0/b/flutter-varios-b4a94.appspot.com/o/exercises_table.PNG?alt=media&token=48836a3d-a34f-41cc-8566-fa6bf623a697

https://firebasestorage.googleapis.com/v0/b/flutter-varios-b4a94.appspot.com/o/pivot_table.PNG?alt=media&token=8cee7aa8-1c90-4c52-9f3f-1096cc6800e2

https://firebasestorage.googleapis.com/v0/b/flutter-varios-b4a94.appspot.com/o/routines_table.PNG?alt=media&token=28322c00-4e8c-48d2-b647-9a94a68f91dc

What I expect is when I add a new routine with exercises using sync, in the controller I need that it deletes or add it depending if the exercise is added or not. This section works perfectly. The issue is that each row in the pivot table has a week_day_id and then must be match with this id.

Now if I add or remove a routine it doesn't care about the week_day_id. it must delete or add all the exercises which has routine_id, exercise_id and week_day_id. Hope u understand what I mean. I have been trying to find a solution here reading the doc, but I can't manage to resolve by myself. Thanks in advance



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire