Laravel 5 - 多对多 - 附加与保存

Laravel 5 - Many to Many - Attach versus Save

我在两个模型、用户和角色之间建立了多对多关系。使用 save() 方法和使用 attach() 方法保存关系有区别吗?

$user->roles()->save($role, ['expires' => $expires]); //using save
$user->roles()->attach($roleId, ['expires' => $expires]);// using attach

两者是等价的吗?我个人看不出有什么区别。想法?

这里是 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]);