Home

hasMany

hasMany is a data relationship used in object-relational mapping and data modeling to express a one-to-many association. In a hasMany relationship, a single instance of a parent model is related to multiple instances of a child model. The foreign key linking the two is typically stored on the child table, pointing to the parent, which means the parent owns a collection of children.

The exact syntax varies by framework, but the concept is the same: the parent exposes a collection

Accessing and manipulating related records is usually straightforward: you can read the collection (e.g., user.posts) and

Performance considerations include the potential for the N+1 query problem if related data is loaded separately.

of
its
children.
Examples
include
Laravel
Eloquent:
public
function
posts()
{
return
$this->hasMany(Post::class);
}.
Rails:
has_many
:posts.
Sequelize:
Parent.hasMany(Child,
{
foreignKey:
'parentId'
}).
In
each
case,
the
child
table
holds
the
foreign
key.
add
new
children
through
the
parent
(e.g.,
user.posts.create({...})
or
by
setting
the
foreign
key
on
a
new
child).
Deletion
rules
and
constraints
are
commonly
configurable,
such
as
cascade
delete
when
the
parent
is
removed.
Eager
loading
can
mitigate
this
by
fetching
parents
and
their
children
in
as
few
queries
as
possible.
hasMany
is
often
paired
with
the
belongsTo
relation
on
the
child
side,
and
it
contrasts
with
many-to-many
relationships
that
require
a
join
table.