Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add getOrder method for dynamic order column support. #179

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/SortableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ public function getLowestOrderNumber(): int
return (int) $this->buildSortQuery()->min($this->determineOrderColumnName());
}

/**
* Get the order value from a dynamically determined column.
*
* This method returns the model's order value from the column specified by `determineOrderColumnName`.
* It allows for flexibility in specifying the order column in different model configurations.
*
* @return int The value of the order column.
*/
public function getOrder() : int
{
$orderColumnName = $this->determineOrderColumnName();

return $this->$orderColumnName;
}

public function scopeOrdered(Builder $query, string $direction = 'asc')
{
return $query->orderBy($this->determineOrderColumnName(), $direction);
Expand Down
29 changes: 29 additions & 0 deletions tests/SortableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Spatie\EloquentSortable\Test;

use Illuminate\Support\Collection;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;

class SortableTest extends TestCase
{
Expand Down Expand Up @@ -423,4 +425,31 @@ public function it_can_tell_if_element_is_last_in_order()
$this->assertTrue($model[$model->count() - 1]->isLastInOrder());
$this->assertFalse($model[$model->count() - 2]->isLastInOrder());
}

/** @test */
public function it_can_determine_custom_column_and_get_order_number()
{
$model = Dummy::first();
$this->assertEquals($model->getOrder(), 1);



$model = new class () extends Dummy {
public $sortable = [
'order_column_name' => 'my_custom_order_column',
];
};
$model->my_custom_order_column = 2;
$this->assertEquals($model->getOrder(), 2);



$model = new class () extends Dummy {
public $sortable = [
'order_column_name' => 'my_other_custom_order_column',
];
};
$model->my_other_custom_order_column = 3;
$this->assertEquals($model->getOrder(), 3);
}
}
Loading