Home

hasone

HasOne is a one-to-one association used in databases, ORMs, and data modeling. It denotes that a single record in the source model is linked to at most one record in the related model. In most implementations the link is established by a foreign key in the related table pointing to the source table.

Conceptually, hasOne differs from belongsTo in the placement of the foreign key. In a hasOne relationship, the

Example in Laravel's Eloquent: class User extends Model { public function profile() { return $this->hasOne(Profile::class); } } class Profile extends

Database schema and constraints: a hasOne relation is implemented by adding a unique foreign key constraint

Performance and usage considerations: hasOne is commonly retrieved via eager loading to minimize queries (for example,

See also: hasMany, belongsTo, OneToOne (terminology varies across frameworks).

foreign
key
typically
resides
on
the
related
model,
while
belongsTo
places
the
foreign
key
on
the
source
model.
This
distinction
affects
how
queries
are
written
and
how
deletions
cascade.
Model
{
public
function
user()
{
return
$this->belongsTo(User::class);
}
}
In
this
setup
the
profiles
table
contains
a
user_id
column
referencing
users.id.
Likewise,
in
Rails
you
would
declare
has_one
:profile
on
the
User
model
and
have
profiles.user_id
as
the
foreign
key.
on
the
related
table
to
enforce
one-to-one,
and
optionally
making
the
foreign
key
non-null
if
a
related
record
is
required.
You
typically
create
an
index
on
the
foreign
key
for
performance.
in
Laravel:
with('profile')).
Deleting
a
parent
may
require
cascading
delete
or
handling
orphaned
records
depending
on
constraints.
When
optional,
the
related
record
may
be
null.