|
| 1 | +# Eager Loading Relationships |
| 2 | + |
| 3 | +`Datatables` support searching and sorting of eager loaded relationships when using `Eloquent`. |
| 4 | +In this example, I will show you how to setup a eager loading search using `EloquentEngine`. |
| 5 | + |
| 6 | +To enable search, we need to eager load the relationship we intend to use using Laravel's `User::with('posts')` api. |
| 7 | + |
| 8 | +```php |
| 9 | +use Datatables; |
| 10 | + |
| 11 | +Route::get('user-data', function() { |
| 12 | + $model = App\User::with('posts'); |
| 13 | + |
| 14 | + return Datatables::eloquent($model) |
| 15 | + ->addColumn('posts', function (User $user) { |
| 16 | + return $user->posts->map(function($post) { |
| 17 | + return str_limit($post->title, 30, '...'); |
| 18 | + })->implode('<br>'); |
| 19 | + }) |
| 20 | + ->make(true); |
| 21 | +}); |
| 22 | +``` |
| 23 | + |
| 24 | +To trigger search on `posts` relationship, we need to specify the `relation.column_name` as the `name` attribute in our `javascript` appropriately. |
| 25 | + |
| 26 | +```php |
| 27 | +<script> |
| 28 | + $(document).ready(function() { |
| 29 | + $('#users-table').DataTable({ |
| 30 | + processing: true, |
| 31 | + serverSide: true, |
| 32 | + ajax: '{{ url("collection/basic-object-data") }}', |
| 33 | + columns: [ |
| 34 | + {data: 'id', name: 'id'}, |
| 35 | + {data: 'name', name: 'name'}, |
| 36 | + {data: 'email', name: 'email'}, |
| 37 | + {data: 'posts', name: 'posts.title'}, |
| 38 | + {data: 'created_at', name: 'created_at'}, |
| 39 | + {data: 'updated_at', name: 'updated_at'} |
| 40 | + ] |
| 41 | + }); |
| 42 | +</script> |
| 43 | +``` |
| 44 | +
|
| 45 | +Looking at `{data: 'posts', name: 'posts.title'},`: |
| 46 | +- `data: posts` represents the data key (`data.posts`) that we are going to display on our table. |
| 47 | +- `name: posts.title` represents the `User` model relationship (`posts`) and the column we are going to perform our search (`title`). |
| 48 | +
|
| 49 | +## Nested Relationships |
| 50 | +Same strategy goes for nested relationships but do **NOTE** that ordering is not yet fully tested on nested relationships. |
| 51 | +
|
0 commit comments