Home

belongsToMany

belongsToMany is a relationship type used to model a many-to-many association between two models in an ORM. In this pattern, an intermediate table called a pivot table stores the associations, with each row linking one record from each side and potentially carrying additional attributes about that link.

In Laravel's Eloquent ORM, the relation is defined on each model with the belongsToMany method. The call

Querying the relation returns a collection of related models. When looping, pivot data is accessible on each

Common operations to manage the relation include attach, detach, and sync. attach and detach add or remove

Example: a posts_tags pivot table connects posts and tags with post_id and tag_id. In Post, public function

can
include
the
related
model
class,
the
pivot
table
name,
and
the
foreign
key
names
for
both
models.
If
these
are
omitted,
conventions
apply:
the
pivot
table
name
is
the
two
model
names
in
alphabetical
snake_case
plural
form,
and
the
foreign
keys
are
the
respective
model
names
suffixed
with
_id
(for
example,
post_id
and
tag_id).
You
can
customize
with
belongsToMany(Tag::class,
'post_tag',
'post_id',
'tag_id').
related
model
via
a
pivot
property,
and
additional
pivot
columns
can
be
retrieved
or
selected
with
withPivot('field').
Enabling
withTimestamps()
on
the
relation
stores
created_at
and
updated_at
on
the
pivot
table.
specific
links;
sync
updates
the
entire
set
to
match
a
given
list
of
IDs,
removing
any
not
present.
You
can
also
update
an
existing
pivot
row
with
updateExistingPivot.
tags()
{
return
$this->belongsToMany(Tag::class)->withTimestamps();
}
In
Tag,
public
function
posts()
{
return
$this->belongsToMany(Post::class)->withTimestamps();
}