Relationships
Eloquentity supports several types of relationships: hasMany
, hasOne
, belongsTo
, and belongsToMany
. Below are examples and explanations for each.
Has Many / Belongs To Many
This example demonstrates defining a hasMany
relationship within a model. The same syntax applies for belongsToMany
relationships.
app/Models/Post.php
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
app/Entities/PostEntity.php
class PostEntity
{
/** @param Comment[] $comments */
public function __construct(
// ...
public readonly array $comments,
// ...
) {
}
}
ℹ️
Entities added to a collection do not require explicit calls to
persist
, as Eloquentity handles this automatically.⚠️
Removing an entity from a collection does not delete it from the database.
Custom Collection Class
Instead of a basic PHP array, you can use any iterable class that accepts an array of items in its constructor as a collection type.
MyCollection.php
class MyCollection implements IteratorAggregate
{
public function __construct(private readonly array $items = [])
{
}
// collection methods...
public function getIterator(): Traversable
{
return new ArrayIterator($this->items);
}
}
app/Entities/PostEntity.php
class PostEntity
{
/** @param MyCollection<Comment> $comments */
public function __construct(
// ...
public readonly MyCollection $comments,
// ...
) {
}
}
hasOne / belongsTo
Below is an example of a belongsTo
relationship, which is similarly applicable to hasOne
.
app/Models/Comment.php
public function post(): BelongsTo
{
return $this->belongsTo(Post::class);
}
app/Entities/CommentEntity.php
use App\Entities\Post;
class CommentEntity
{
public function __construct(
// ...
public readonly Post $post,
// ...
) {
}
}