Laravel - Relationships - One To One
A one-to-one relationship is a very basic type of database relationship. For example, a User
model might be associated with one Phone
model. To define this relationship, we will place a phone
method on the User
model. The phone
method should call the hasOne
method and return its result. The hasOne
method is available to your model via the model's Illuminate\Database\Eloquent\Model
base class:
hasOne(Phone::class);
}
}
The first argument passed to the hasOne
method is the name of the related model class. Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:
$phone = User::find(1)->phone;
Eloquent determines the foreign key of the relationship based on the parent model name. In this case, the Phone
model is automatically assumed to have a user_id
foreign key. If you wish to override this convention, you may pass a second argument to the hasOne
method:
return $this->hasOne(Phone::class, 'foreign_key');
Additionally, Eloquent assumes that the foreign key should have a value matching the primary key column of the parent. In other words, Eloquent will look for the value of the user's id
column in the user_id
column of the Phone
record. If you would like the relationship to use a primary key value other than id
or your model's $primaryKey
property, you may pass a third argument to the hasOne
method:
return $this->hasOne(Phone::class, 'foreign_key', 'local_key');