Skip to content

Commit 044f9c2

Browse files
authored
Merge pull request #16 from SalemC/update-documentation-to-explain-foreign-key-relational-mapping-support
Introduce documentation for relational support
2 parents 0e9ad19 + 287da8b commit 044f9c2

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ Options:
2424
```
2525

2626
## Example Usage
27+
2728
Invocating `php artisan typescriptify:model \App\Models\User` on a fresh Laravel installation will produce:
2829

2930
```ts
@@ -45,6 +46,48 @@ use SalemC\TypeScriptifyLaravelModels\TypeScriptifyModel;
4546
echo (new TypeScriptifyModel(\App\Models\User::class))->generate();
4647
```
4748

49+
## Relation Mapping
50+
51+
**TypeScriptify Laravel Models** supports `belongsTo` relation mapping.
52+
53+
Imagine you have the following scenario:
54+
55+
```php
56+
// app/Models/User.php
57+
// columns: id, name, email, password, role_id
58+
59+
public function role(): BelongsTo {
60+
return $this->belongsTo(Role::class);
61+
}
62+
63+
// app/Models/Role.php
64+
// columns: id, name
65+
66+
public function roles(): HasMany {
67+
return $this->hasMany(User::class);
68+
}
69+
```
70+
71+
With a foreign key (**and a foreign key constraint**) `role_id` on the `users` table.
72+
73+
It would be nice if instead of having a `role_id: number` attribute on the generated `User` interface, it was instead the full relational dataset, right? Well, **TypeScriptify Laravel Models** is able to recognise that the `role_id` column should be the `Role` model, and will map it to a reusable interface definition for you. Unfortunately, we're not able to determine the exact relation name; instead we attempt to guess it for you, based on the foreign key name:
74+
75+
```ts
76+
// Automatically generated Role interface.
77+
interface Role {
78+
id: number;
79+
name: string;
80+
}
81+
82+
interface User {
83+
id: number;
84+
name: string;
85+
email: string;
86+
password: string;
87+
role: Role; // 'guessed' attribute name of 'role' (from 'role_id') with the interface Role, generated above.
88+
}
89+
```
90+
4891
## How It Works
4992

5093
### Database

0 commit comments

Comments
 (0)