简体   繁体   中英

Laravel datatable sorting issue

I'm using Laravel - data tables by yajra https://github.com/yajra/laravel-datatables-docs

It works perfectly with a single table, but things get serious when I use the eloquent relationship with it. As described below in code I'm showing user name in the table, it showing user name perfectly fine but when I try to sort on User or simply search it gives me a wrong error or shows SQL error.

I have following eloquent models

class Project extends Model{
     public function client(){
      return $this->belongsTo(Client::class);
     }
}
class Client extends Model{
     public function user(){
          return $this->belongsTo(User::class);
     }
}
class User extends Model{
}

HTML

<table id="table">
    <tbody>
        <tr>
            <td>Name</td>
            <td>Start Date</td>
            <td>Target</td>
            <td>User</td>
        </tr>
    </tbody>
</table>

Javascript

$("#table").DataTable({
        processing: true,
        serverSide: true,
        autoWidth:false,
        ajax: '/projects',
        columns:[
            { data: 'project_name', name: 'project_name' },
            { data: 'start_date', name: 'start_date' },
            { data: 'target', name: 'target' },
            { data: 'client.user.name', name: 'client.user.name' }
        ]
    });

Project Controller

public function projects(){
    return Datatables::of(Proejct::with(['client.user']))
            ->addColumn("client.user.name", function($row){
                return $row->client->user->name;
            })->make(true);
}

It doesn't not support multi level of eloquent relationship sorting or search. So you will get data but you can't search or sort on them.

Your code seems okay and it will work perfectly for single level.

Here's more details about the issue. https://github.com/yajra/laravel-datatables/issues/993

返回 $row->client()->user()->name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM