Skip to content

Commit e71fc3b

Browse files
committed
fix: Custom Order on eager loaded relationships was not working
1 parent 7917f7a commit e71fc3b

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-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+
} else if ($this->hasOrderColumn($column)) {
635637
$this->applyOrderColumn($column, $orderable);
636638
} else {
637639
$nullsLastSql = $this->getNullsLastSql($column, $orderable['direction']);
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
function it_can_order_with_custom_order()
16+
{
17+
$response = $this->getJsonResponse([
18+
'order' => [
19+
[
20+
'column' => 1,
21+
'dir' => 'asc',
22+
],
23+
],
24+
'length' => 10,
25+
'start' => 0,
26+
'draw' => 1,
27+
]);
28+
29+
$response->assertJson([
30+
'draw' => 1,
31+
'recordsTotal' => 60,
32+
'recordsFiltered' => 60,
33+
]);
34+
35+
$this->assertEquals($response->json()['data'][0]['user']['id'], collect($response->json()['data'])->pluck('user.id')->max());
36+
}
37+
38+
protected function getJsonResponse(array $params = [])
39+
{
40+
$data = [
41+
'columns' => [
42+
['data' => 'user.id', 'name' => 'user.name', 'searchable' => 'true', 'orderable' => 'true'],
43+
['data' => 'user.email', 'name' => 'user.email', 'searchable' => 'true', 'orderable' => 'true'],
44+
['data' => 'title', 'name' => 'posts.title', 'searchable' => 'true', 'orderable' => 'true'],
45+
],
46+
];
47+
48+
return $this->call('GET', '/relations/belongsTo', array_merge($data, $params));
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.email', function ($query, $order) {
58+
$query->orderBy('users.id', $order == 'desc' ? 'asc' : 'desc');
59+
})->toJson();
60+
});
61+
}
62+
}

0 commit comments

Comments
 (0)