mercredi 25 octobre 2017

Laravel - Table has no primary key = updating all records when doing a save

Working on a 'legacy' Lavaral project that has some database structure issues.

There is a pivot table that links services to a user. The issue is that there is no primary key on the table. Instead it has the following:

id (relates to service_id)
user_id
duration
price

The issue is that when updating a single users services information it is actually updating every record in the database where the id (service_id) is the same.

An example: 2 users have the following in the database

id = 1, user_id = 1, duration = null, price = null
id = 1, user_id = 2, duration = null, price = null

The service id of 1 references the ID of a record within the services table.

There is a modal that does an API call for a user to update a specific service, this endpoint (condensed) looks like this:

foreach ($request->services as $key => $value) {
    $serviceRecord = ServiceUser::where('user_id', $userId)->where('id', $value['id'])->first();

    $serviceRecord->duration = ($value['duration'] ? $value['duration'] : null);
    $serviceRecord->price = ($value['price'] ? $value['price'] : null);
    $serviceRecord->save();
}

This currently is updating both of the users records with the same price / duration information.

My issue is that this is now quite a large project and there are countless references to the ServiceUser's id field. Is there a way to make this save only update the record that is returned when doing the first() method? Or do I need to go through the whole app and change it so it uses a primary key for this table?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire