I have a table called event_speakers
. In the app, a user can click on a
icon and add as many speakers as they want.
I'm using a for loop and then Laravel's createMany
method.
The problem is that the order of the speakers is coming out wrong when I fetch them from the db, and I can't sort them because the created_at
and updated_at
columns in the database are all exactly the same.
Is there a way to somehow add a second or a few milliseconds in between each record so that the created_at
date and time are not all exactly the same?
Here is my code that successfully inserts the data:
for ($i = 0; $i < $numRecords; $i ) {
if ($request->speaker_name_en[$i] != null) {
$data[] = [
'photo' => $this->uploadImage($livestream, $client, $request['speaker_image_en'][$i]),
'name_en' => $request->speaker_name_en[$i],
'name_fr' => $request->speaker_name_fr[$i],
'title_en' => $request->speaker_title_en[$i],
'subtitle_en' => $request->speaker_subtitle_en[$i],
'description_en' => $request->speaker_description_en[$i],
'title_fr' => $request->speaker_title_fr[$i],
'subtitle_fr' => $request->speaker_subtitle_fr[$i],
'description_fr' => $request->speaker_description_fr[$i],
'client_id' => $client->id
];
}
}
if (isset($data)) {
$client->eventspeakers()->createMany($data);
}
Any ideas?
CodePudding user response:
Why not orderBy() a different column? https://laravel.com/docs/9.x/queries#ordering-grouping-limit-and-offset
You could also specify the created_at
and add a second each iteration
for ($i = 0; $i < $numRecords; $i ) {
if ($request->speaker_name_en[$i] != null) {
$data[] = [
'photo' => $this->uploadImage($livestream, $client, $request['speaker_image_en'][$i]),
'name_en' => $request->speaker_name_en[$i],
'name_fr' => $request->speaker_name_fr[$i],
'title_en' => $request->speaker_title_en[$i],
'subtitle_en' => $request->speaker_subtitle_en[$i],
'description_en' => $request->speaker_description_en[$i],
'title_fr' => $request->speaker_title_fr[$i],
'subtitle_fr' => $request->speaker_subtitle_fr[$i],
'description_fr' => $request->speaker_description_fr[$i],
'client_id' => $client->id,
'created_at' => now()->addSeconds($i),
];
}
}
if (isset($data)) {
$client->eventspeakers()->createMany($data);
}
CodePudding user response:
When you fetch your speakers data, you can sort them directly by ID instead of created_at