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
+48Lines changed: 48 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -317,6 +317,54 @@ LEFT JOIN payments ON payments.contract_id = contracts.id
317
317
318
318
The same optional parameters as `HasOneThrough` are available for custom join fields: `ownerJoin`, `relationJoin`, `throughOwnerJoin`, and `throughRelationJoin`.
319
319
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 ONauthors_tags.author_id=authors.id
346
+
LEFT JOIN tags ONtags.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
+
320
368
### Using UUIDs as primary keys
321
369
322
370
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