Skip to content

Commit af7a1fc

Browse files
committed
Add relationship docs.
1 parent 0c1bf45 commit af7a1fc

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

documentation.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
- [Query Builder Extension](/docs/{{package}}/{{version}}/query-builder)
4343
- [Regex Search](/docs/{{package}}/{{version}}/regex)
4444
- [Smart Search](/docs/{{package}}/{{version}}/smart-search)
45+
- [Relationships](/docs/{{package}}/{{version}}/relationships)
4546
- Sorting/Ordering
4647
- [Manual Order](/docs/{{package}}/{{version}}/manual-order)
4748
- [Order Column](/docs/{{package}}/{{version}}/order-column)

relationships.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
 (0)