简体   繁体   English

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

[英]Laravel 5 - Many to Many - Attach versus Save

I have a many to many relationship between two models, users and roles. 我有两个模型,用户和角色之间的多对多关系。 Is there a difference between saving a relationship using the save() method and using the attach() method? 使用save()方法保存关系和使用attach()方法之间有区别吗?

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

Are the two equivalent? 这两个是等价的吗? I personally dont see the difference. 我个人没有看到差异。 Thoughts? 思考?

Here is the snippet of code for the save() method. 这是save()方法的代码片段。 You'll see that it eventually calls attach() . 你会看到它最终调用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;
}

One big difference is that it also saves the model that you are passing to it. 一个很大的区别是它还可以保存您传递给它的模型。 In other words, you can essentially create a new role (or even update the old one) while also attaching it to the user. 换句话说,您实际上可以创建一个新角色(甚至更新旧角色),同时将其附加到用户。 For example: 例如:

// 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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM