{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
one to one
hasOne/belongsTo
one to many
hasMany/belongsTo
many to many
belongsToMany/belongsToMany
$shop = Shop::find($shop_id);
$shop->products()->attach($product_id);
$shop->products()->detach($product_id);
we may access the intermediate table using the pivot attribute on the models:
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
Notice that each Role model we retrieve is automatically assigned a pivot attribute. This attribute contains a model representing the intermediate table, and may be used like any other Eloquent model.
Filtering Relationships Via Intermediate Table Columns
return $this->belongsToMany('App\Role')->wherePivot('approved', 1);
return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);
Inserting & Updating Related Models
setting the post_id attribute on the Comment$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);
$post->comments()->saveMany([
new App\Comment(['message' => 'A new comment.']),
new App\Comment(['message' => 'Another comment.']),
]);
$post = App\Post::find(1);
$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';
$post->push();
the difference between save and create is that save accepts a full Eloquent model instance while create accepts a plain PHP array:
$post = App\Post::find(1);
$comment = $post->comments()->create([
'message' => 'A new comment.',
]);
$post->comments()->createMany([
[
'message' => 'A new comment.',
],
[
'message' => 'Another new comment.',
],
]);
Belongs To Relationships
When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();
$user->account()->dissociate();
$user->save();
Many To Many Relationships
$user = App\User::find(1);$user->roles()->attach($roleId);
When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:
$user->roles()->attach($roleId, ['expires' => $expires]);
$user->roles()->detach($roleId);
// Detach all roles from the user...
$user->roles()->detach();
When working with a many-to-many relationship, the save method accepts an array of additional intermediate table attributes as its second argument:
App\User::find(1)->roles()->save($role, ['expires' => $expires]);
updateExistingPivot method. This method accepts the pivot record foreign key and an array of attributes to update:
$user = App\User::find(1);
$user->roles()->updateExistingPivot($roleId, $attributes);