lifesound's avatar

Eloquent mass updates to a collection of models

I have a collection of products

I have generated ( different ) SKU for each one

could I send them ( update them ) in one query?

0 likes
1 reply
Tray2's avatar
Tray2
Best Answer
Level 74

You can't, unless they all should get the same update.

Eloquent is just a wrapper to SQL, and you need to handle each product on it's own.

I've done this to update the tracks of a record.

 public function updateTracks(array $tracksArray, ForeignKeyService $foreignKeyService): void
    {
        $tracks = Track::query()
            ->where('record_id', $tracksArray['record_id'])
            ->get();

        $i = 0;

        foreach ($tracks as $track) {
            $track->position = Str::padLeft($tracksArray['track_positions'][$i], 2, '0');
            $track->title = $tracksArray['track_titles'][$i];
            $track->duration = $tracksArray['track_durations'][$i];
            $track->mix = $tracksArray['track_mixes'][$i];
            if ($this->isVariousArtists($tracksArray['record_artist'])) {
                $track->artist_id = $foreignKeyService->getArtistId($tracksArray['track_artists'][$i]);
            }
            $track->save();
            $i++;
        }
    }
1 like

Please or to participate in this conversation.