Skip to content

Commit ba76b9b

Browse files
committed
docs: add BelongsToMany relationship documentation
1 parent 163d76a commit ba76b9b

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

docs/1-essentials/03-database.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,54 @@ LEFT JOIN payments ON payments.contract_id = contracts.id
317317

318318
The same optional parameters as `HasOneThrough` are available for custom join fields: `ownerJoin`, `relationJoin`, `throughOwnerJoin`, and `throughRelationJoin`.
319319

320+
### Belongs to many
321+
322+
The {b`#[Tempest\Database\BelongsToMany]`} attribute defines a many-to-many relationship using a pivot table. Both sides of the relationship can declare the attribute.
323+
324+
```php
325+
use Tempest\Database\BelongsToMany;
326+
327+
final class Author
328+
{
329+
/** @var \App\Tag\Tag[] */
330+
#[BelongsToMany]
331+
public array $tags = [];
332+
}
333+
334+
final class Tag
335+
{
336+
/** @var \App\Author\Author[] */
337+
#[BelongsToMany]
338+
public array $authors = [];
339+
}
340+
```
341+
342+
The pivot table name is inferred alphabetically from both model table names (e.g., `authors` + `tags` = `authors_tags`). This generates SQL like:
343+
344+
```sql
345+
LEFT JOIN authors_tags ON authors_tags.author_id = authors.id
346+
LEFT JOIN tags ON tags.id = authors_tags.tag_id
347+
```
348+
349+
A custom pivot table name and join fields can be specified:
350+
351+
```php
352+
#[BelongsToMany(
353+
pivot: 'custom_pivot_table',
354+
ownerJoin: 'custom_author_fk',
355+
relationJoin: 'uuid',
356+
relatedOwnerJoin: 'custom_tag_fk',
357+
relatedRelationJoin: 'uuid',
358+
)]
359+
public array $tags = [];
360+
```
361+
362+
- `pivot`: Custom pivot table name
363+
- `ownerJoin`: FK on pivot pointing to the owner model
364+
- `relationJoin`: PK on the owner model
365+
- `relatedOwnerJoin`: FK on pivot pointing to the related model
366+
- `relatedRelationJoin`: PK on the related model
367+
320368
### Using UUIDs as primary keys
321369

322370
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)