Skip to content

Commit fd0f292

Browse files
committed
docs: add HasOneThrough relationship documentation
1 parent 1031cf7 commit fd0f292

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

docs/1-essentials/03-database.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,49 @@ final class Book
250250
}
251251
```
252252

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 ON profiles.author_id = authors.id
275+
LEFT JOIN addresses ON addresses.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+
253296
### Using UUIDs as primary keys
254297

255298
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

Comments
 (0)