Column Order Number Error

Hi, I'm trying to use column_order for my relation manager. This is my code: Track Model
public function releases()
{
return $this->belongsToMany(Release::class, 'track_album', 'track_id', 'release_id')
->withPivot('track_order')
->orderBy('track_order');
}
public function releases()
{
return $this->belongsToMany(Release::class, 'track_album', 'track_id', 'release_id')
->withPivot('track_order')
->orderBy('track_order');
}
Release Model
public function tracks()
{
return $this->belongsToMany(Track::class, 'track_album', 'release_id', 'track_id')
->withPivot('track_order')
->orderBy('track_album.track_order');
}

public function addTrack(Track $track)
{
$maxOrder = $this->tracks()->max('track_order') ?? 0;
$this->tracks()->attach($track->id, ['track_order' => $maxOrder + 1]);
}
public function tracks()
{
return $this->belongsToMany(Track::class, 'track_album', 'release_id', 'track_id')
->withPivot('track_order')
->orderBy('track_album.track_order');
}

public function addTrack(Track $track)
{
$maxOrder = $this->tracks()->max('track_order') ?? 0;
$this->tracks()->attach($track->id, ['track_order' => $maxOrder + 1]);
}
Relation manager
->reorderable(fn () => str($this->getPageClass())->contains('TrackList') ? 'track_order' : null)
->defaultSort('track_order')
->reorderRecordsTriggerAction(
fn (ActionsAction $action, bool $isReordering) => $action
->button()
->label($isReordering ? 'Cancel Reordering' : 'Reorder Tracks')
)
->reorderable(fn () => str($this->getPageClass())->contains('TrackList') ? 'track_order' : null)
->defaultSort('track_order')
->reorderRecordsTriggerAction(
fn (ActionsAction $action, bool $isReordering) => $action
->button()
->label($isReordering ? 'Cancel Reordering' : 'Reorder Tracks')
)
Why when I create/attach data, the column_order (in my case track_order) is not auto created? I need to reorder it first so the order number is showed and save into database. Is this a bug or what? because I didn't get this error before
3 Replies
kisut
kisut4w ago
Sorry for the last file
kisut
kisut4w ago
Up
Bruno Pereira
Bruno Pereira3w ago
It's not a bug, You have to set it manually. If in your database you didnt define a default value the data is null if column is nullable. What I do is when I create the record I count all the models and set the sort column to be $totalcount + 1. Ex: If you have 5 tracks already on DB, when I create another, the order will be 6 because 5 + 1
Tables\Actions\AttachAction::make()
->after(function(Model $model) {
$model->update(['sort' => Model::count() + 1]);
}),
Tables\Actions\AttachAction::make()
->after(function(Model $model) {
$model->update(['sort' => Model::count() + 1]);
}),
Something like that (not tested)
Want results from more Discord servers?
Add your server