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

ala*_*udi 14 php save laravel

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

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

这两个是等价的吗?我个人没有看到差异.思考?

Tho*_*Kim 18

这是该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;
}
Run Code Online (Sandbox Code Playgroud)

一个很大的区别是它还可以保存您传递给它的模型.换句话说,您实际上可以创建一个新角色(甚至更新旧角色),同时将其附加到用户.例如:

// 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]);
Run Code Online (Sandbox Code Playgroud)

  • 很棒的答案 (2认同)