克隆一个包含所有关系的 Eloquent 对象? [英] Clone an Eloquent object including all relationships?

查看:19
本文介绍了克隆一个包含所有关系的 Eloquent 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以轻松地克隆一个 Eloquent 对象,包括它的所有关系?

Is there any way to easily clone an Eloquent object, including all of its relationships?

例如,如果我有这些表:

For example, if I had these tables:

users ( id, name, email )
roles ( id, name )
user_roles ( user_id, role_id )

除了在users表中新建一行,除了id之外的所有列都相同,还应该在中新建一行user_roles 表,为新用户分配相同的角色.

In addition to creating a new row in the users table, with all columns being the same except id, it should also create a new row in the user_roles table, assigning the same role to the new user.

像这样:

$user = User::find(1);
$new_user = $user->clone();

用户模型在哪里

class User extends Eloquent {
    public function roles() {
        return $this->hasMany('Role', 'user_roles');
    }
}

推荐答案

在 laravel 4.2 中测试了belongsToMany 关系

tested in laravel 4.2 for belongsToMany relationships

如果您在模型中:

    //copy attributes
    $new = $this->replicate();

    //save model before you recreate relations (so it has an id)
    $new->push();

    //reset relations on EXISTING MODEL (this way you can control which ones will be loaded
    $this->relations = [];

    //load relations on EXISTING MODEL
    $this->load('relation1','relation2');

    //re-sync everything
    foreach ($this->relations as $relationName => $values){
        $new->{$relationName}()->sync($values);
    }

这篇关于克隆一个包含所有关系的 Eloquent 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆