下面是该方法的代码片段。您将看到它最终会调用 .save()
attach()
/**
* Save a new model and attach it to the parent model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param array $joining
* @param bool $touch
* @return \Illuminate\Database\Eloquent\Model
*/
public function save(Model $model, array $joining = [], $touch = true)
{
$model->save(['touch' => false]);
$this->attach($model->getKey(), $joining, $touch);
return $model;
}
一个很大的区别是,它还保存了您要传递给它的模型。换句话说,您基本上可以创建新角色(甚至更新旧角色),同时将其附加到用户。例如:
// Get the user
$user = User::first();
// Instantiate a new role
$role = new Role($attributes);
// Creates the role / persists it into the database and attaches this role to the user
$user->roles()->save($role, ['expires' => $expires]);