Skip to content

Commit 0c8ec45

Browse files
authored
Add one-of-many-example
1 parent 6899299 commit 0c8ec45

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

docs/misc/one-of-many-example.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
---
2+
title: One Of Many Example
3+
weight: 8
4+
---
5+
6+
When trying to retrieve "OneOfMany", you may experience duplicate records.
7+
8+
Core functionality for this will be added in due course, this is simply a work-around.
9+
10+
In the meantime, to avoid this, you can use the following approach.
11+
12+
This example assumes two Models:
13+
User -> HasMany -> Things
14+
15+
### Models
16+
#### User
17+
id
18+
name
19+
created_at
20+
updated_at
21+
etc
22+
23+
```php
24+
public function things(): \Illuminate\Database\Eloquent\Relations\HasMany
25+
{
26+
return $this->hasMany(Things::class);
27+
}
28+
```
29+
30+
#### Things
31+
id
32+
name
33+
user_id
34+
created_at
35+
updated_at
36+
37+
### Table
38+
The following is the table code for this example, and retrieves the most recently created "Thing"
39+
40+
#### Column
41+
```php
42+
Column::make('Latest Thing')
43+
->label(
44+
fn ($row, Column $column) => $row->things->first()->name
45+
),
46+
```
47+
48+
#### Builder
49+
```php
50+
public function builder(): Builder {
51+
52+
return User::query()->with(['things' => function ($query) {
53+
$query->select(['id','user_id','name'])->orderBy('created_at', 'desc')->limit(1);
54+
}]);
55+
56+
}
57+
```
58+
59+
Core functionality for this will be added in due course, this is simply a work-around.

0 commit comments

Comments
 (0)