You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/1-essentials/03-database.md
+43Lines changed: 43 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -250,6 +250,49 @@ final class Book
250
250
}
251
251
```
252
252
253
+
### Has one through
254
+
255
+
The {b`#[Tempest\Database\HasOneThrough]`} attribute defines a one-to-one relationship that traverses an intermediate model. This lets you access a distant relation directly, resolved in a single SQL query with two JOINs.
256
+
257
+
```php
258
+
use Tempest\Database\HasOne;
259
+
use Tempest\Database\HasOneThrough;
260
+
261
+
final class Author
262
+
{
263
+
#[HasOne]
264
+
public ?Profile $profile = null;
265
+
266
+
#[HasOneThrough(Profile::class)]
267
+
public ?Address $address = null;
268
+
}
269
+
```
270
+
271
+
The `through` parameter specifies the intermediate model class. The target model is inferred from the property type. This generates SQL like:
272
+
273
+
```sql
274
+
LEFT JOIN profiles ONprofiles.author_id=authors.id
275
+
LEFT JOIN addresses ONaddresses.profile_id=profiles.id
276
+
```
277
+
278
+
When conventions don't match, optional parameters can override the join fields:
279
+
280
+
```php
281
+
#[HasOneThrough(
282
+
through: Profile::class,
283
+
ownerJoin: 'custom_author_fk',
284
+
relationJoin: 'uuid',
285
+
throughOwnerJoin: 'custom_profile_fk',
286
+
throughRelationJoin: 'uuid',
287
+
)]
288
+
public ?Address $address = null;
289
+
```
290
+
291
+
-`ownerJoin`: FK on the intermediate table pointing to the owner
292
+
-`relationJoin`: PK on the owner table
293
+
-`throughOwnerJoin`: FK on the target table pointing to the intermediate
294
+
-`throughRelationJoin`: PK on the intermediate table
295
+
253
296
### Using UUIDs as primary keys
254
297
255
298
By default, Tempest uses auto-incrementing integers as primary keys. UUIDs can be used as primary keys instead by annotating the {b`Tempest\Database\PrimaryKey`} property with the {b`#[Tempest\Database\Uuid]`} attribute. Tempest automatically generates a UUID v7 when a new model is created:
0 commit comments