Belongs To Relationships
A belongsTo() relationship matches a related table's 'id' to a 'localKey' field on 'this' model. Another way to think about it is the belongsTo() relationship should live on the model that has the field that links to the related tables id.
When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:
public function index()
{
$BankAccount = App\BankAccount::find(10);
$user->BankAccount()->associate($account);
$user->save();
}
When removing a belongsTo relationship, you may use the dissociate method. This method will set the relationship's foreign key to null:
public function index()
{
$BankAccount = App\BankAccount::find(10);
$user->BankAccount()->dissociate();
$user->save();
}
Default Models
The belongsTo, hasOne, hasOneThrough, and morphOne relationships allow you to define a default model that will be returned if the given relationship is null. This pattern is often referred to as the Null Object pattern and can help remove conditional checks in your code. In the following example, the user relation will return an empty App\User model if no user is attached to the post:
public function user()
{
return $this->belongsTo('App\User')->withDefault();
}
To populate the default model with attributes, you may pass an array or Closure to the withDefault method:
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault([
'name' => 'Guest Author',
]);
}
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault(function ($user, $post) {
$user->name = 'Guest Author';
});
}