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

标签 php laravel 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]);

关于php - Laravel 5 - 多对多 - 附加与保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35756469/

相关文章:

php - 每张幻灯片的元素响应

php - 基于用户输入的计时器 PHP

php - 显示特定自定义帖子类型的所有帖子及其帖子元

Python Pickle 在 Windows 中加载时崩溃

C:如何从文件加载列表并将其保存在程序末尾

php - 显示存储在 MySQL 数据库 PHP 中的 PDF 文件

php - Blade 模板语法错误,意外 '}' - laravel 5

php - Laravel Eloquent where not in 和 where 条件不起作用

php - 当尝试按关系中的多个记录进行排序时,GROUP BY 子句并包含非聚合列

javascript - 伊宏。如何保存多张属性变化的图像?