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?

$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;
}

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

Laravel相关问答推荐

在没有lang/*.json文件的情况下在Laravel项目中实现多语言支持

为什么只删除了最后一个Like,而没有删除选中的?

Dompdf 古吉拉特语和印地语文本未正确显示

使用两个日期之间的范围获取两列之间的记录,同时搜索过滤条件

在 Laravel 中设置多个 Vue 组件的问题

指令allow_call_time_pass_reference警告

Laravel 中间件返回(try 获取非对象的属性 headers)错误

Carbon(laravel)处理无效日期

使用 Eloquent (Laravel) 在 Group By 之前排序

Laravel 5.2 中的正则表达式验证

在 Laravel 5 中扩展请求类

localhost 和stream_socket_enable_crypto():SSL 操作失败,代码为 1

SQLSTATE [42000]:语法错误或访问冲突:1066 Not unique table/alias on relationship

错误:您的要求无法解析为一组可安装的软件包.

如何利用 StorageFacade 的 Filesystem 类的 glob 方法?

如何在 laravel 中解码 Json 对象并在 laravel 中应用 foreach 循环

从 Artisan 电话中获得响应

Laravel - 动态创建表(无需迁移)

Laravel 不活动时间设置

Laravel:array_merge():参数#2不是数组错误