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

时间:2016-03-02 19:33:30

标签: php laravel save

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

ModelState.AddModelError("Amount", "Greater than 2 please");

两者是否相同?我个人没有看到差异。想法?

1 个答案:

答案 0 :(得分:16)

以下是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]);