Skip to content

Commit a55730b

Browse files
authored
Merge pull request #2906 from Arkhas/fix_custom_order_on_eager_load_relationship
fix: Custom Order on eager loaded relationships was not working
2 parents 4bceed0 + 4af0d08 commit a55730b

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

src/QueryDataTable.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -631,7 +631,9 @@ protected function defaultOrdering(): void
631631
->each(function ($orderable) {
632632
$column = $this->resolveRelationColumn($orderable['name']);
633633

634-
if ($this->hasOrderColumn($column)) {
634+
if ($this->hasOrderColumn($orderable['name'])) {
635+
$this->applyOrderColumn($orderable['name'], $orderable);
636+
} elseif ($this->hasOrderColumn($column)) {
635637
$this->applyOrderColumn($column, $orderable);
636638
} else {
637639
$nullsLastSql = $this->getNullsLastSql($column, $orderable['direction']);

tests/Integration/CustomOrderTest.php

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
3+
namespace Yajra\DataTables\Tests\Integration;
4+
5+
use Illuminate\Foundation\Testing\DatabaseTransactions;
6+
use Yajra\DataTables\DataTables;
7+
use Yajra\DataTables\Tests\Models\Post;
8+
use Yajra\DataTables\Tests\TestCase;
9+
10+
class CustomOrderTest extends TestCase
11+
{
12+
use DatabaseTransactions;
13+
14+
/** @test */
15+
public function it_can_order_with_custom_order()
16+
{
17+
$response = $this->getJsonResponse([
18+
'order' => [
19+
[
20+
'column' => 0,
21+
'dir' => 'asc',
22+
],
23+
],
24+
]);
25+
26+
$this->assertEquals(
27+
$response->json()['data'][0]['user']['id'],
28+
collect($response->json()['data'])->pluck('user.id')->max()
29+
);
30+
}
31+
32+
protected function getJsonResponse(array $params = [])
33+
{
34+
$data = [
35+
'columns' => [
36+
['data' => 'user.id', 'name' => 'user.id', 'searchable' => 'true', 'orderable' => 'true'],
37+
['data' => 'title', 'name' => 'posts.title', 'searchable' => 'true', 'orderable' => 'true'],
38+
],
39+
'length' => 10,
40+
'start' => 0,
41+
'draw' => 1,
42+
];
43+
44+
return $this->call(
45+
'GET',
46+
'/relations/belongsTo',
47+
array_merge($data, $params)
48+
);
49+
}
50+
51+
protected function setUp(): void
52+
{
53+
parent::setUp();
54+
55+
$this->app['router']->get('/relations/belongsTo', function (DataTables $datatables) {
56+
return $datatables->eloquent(Post::with('user')->select('posts.*'))
57+
->orderColumn('user.id', function ($query, $order) {
58+
$query->orderBy('users.id', $order == 'desc' ? 'asc' : 'desc');
59+
})
60+
->toJson();
61+
});
62+
}
63+
}

0 commit comments

Comments
 (0)