Many to Many
The ManyToMany
relationship links multiple entities to multiple related entities. For example, if each post can have multiple tags and each tag can be associated with multiple posts, this relationship can be annotated in the Post
and Tag
entities.
app/Entities/Post.php
<?php
declare(strict_types=1);
namespace App\Entities;
use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Entity;
use Cycle\Annotated\Annotation\Relation\ManyToMany;
#[Entity]
class Post
{
#[Column(type: 'primary')]
private $id;
#[Column(type: 'string')]
private $title;
#[Column(type: 'text')]
private $content;
#[ManyToMany(target: 'App\Entities\Tag', though: 'App\Entities\PostTag')]
private $tags;
}
app/Entities/Tag.php
<?php
declare(strict_types=1);
namespace App\Entities;
use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Entity;
use Cycle\Annotated\Annotation\Relation\ManyToMany;
#[Entity]
class Tag
{
#[Column(type: 'primary')]
private $id;
#[Column(type: 'string')]
private $name;
#[ManyToMany(target: App\Entities\Post::class, though: 'App\Entities\PostTag')]
private $posts;
}