【问题标题】:Laravel 5 - Many to Many - Attach versus SaveLaravel 5 - 多对多 - 附加与保存
【发布时间】:2016-06-15 20:26:40
【问题描述】:

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

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

两者是等价的吗?我个人看不出有什么区别。想法?

【问题讨论】:

    标签: php laravel save


    【解决方案1】:

    这是save() 方法的sn-p 代码。你会看到它最终调用了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]);
    

    【讨论】:

    • 如果我 save() 一个新角色给角色表中不存在的用户,它会在角色数据库中创建一个新角色记录吗?所以基本上使用 save() 永远不会给我们一个错误,但是如果角色不存在,使用 attach() 可能会给我们一个外键错误?
    • @alaboudi 从某种意义上说,是的,但我相信attach() 也不会在您传递模型的新实例时抛出错误。它只是不会附加任何东西,因为该模型在数据库中不存在。但是,save() 将执行额外的步骤,如果它不存在,则首先将其保存到数据库中,如果需要在附加之前更新它,则更新它。
    猜你喜欢
    • 1970-01-01
    • 2017-07-04
    • 2020-11-10
    • 2017-06-08
    • 2018-12-16
    • 1970-01-01
    • 2016-06-20
    • 2017-08-20
    • 1970-01-01
    相关资源
    最近更新 更多