Fix sort order values for existing set of models
3
The Sortable
trait as well as the ReorderController
behaviour require all models to have a consistent sort_order
value.
If you are adding the Sortable
trait for an existing set of models, you might get the following error message when trying to sort the models via the backend:
Illuminate\Database\QueryException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column `db`.`acme_plugin_table`.`sort_order` at row 1
This is because all of your models currently have a sort_order
value of NULL
or 0
.
To fix this issue, simply run the following statement in a php artisan tinker
session. It will set initial sort_order
values for each model.
You can set the inital order by editing the orderBy
statement according to your data.
Vendor\YourPlugin\Models\YourModel
::orderBy('title') // Change this to modify the inital order
->get()
->map(function($model, $index) {
$model->sort_order = $index + 1;
$model->save();
});
Console friendly version for pasting after your model query:
->get()->map(function($model, $index) {$model->sort_order = $index + 1;$model->save();});
There are no comments yet
Be the first one to comment