克隆一个雄辩的对象,包括所有的关系? [英] Clone an Eloquent object including all relationships?
本文介绍了克隆一个雄辩的对象,包括所有的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,如果我有这些表:
用户(id,name,email)
roles(id,name)
user_roles(user_id,role_id)
除了在用户
表中创建新行外,除了 id
之外,所有列都相同,它还应该在 user_roles
表中创建一个新行,分配相同
如下所示:
$ user = User :: find(1);
$ new_user = $ user-> clone();
用户模型有哪些
class User Eloquent {
public function roles(){
return $ this-> hasMany('Role','user_roles');
}
}
解决方案
在Laravel 4.2 for belongsToMany关系
如果你在模型中:
//复制属性
$ new = $ this-> replicate();
//在重新建立关系之前保存模型(所以有一个id)
$ new-> push();
//在现有的模型中重新设置关系(这样你可以控制哪一个将被加载
$ this-> relations = [];
//负载关系在现在的模型
$ this-> load('relation1','relation2');
//重新同步所有
foreach($ this->关系为$ relationName => $ values){
$ new-> {$ relationName}() - > sync($ values);
}
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 )
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.
Something like this:
$user = User::find(1);
$new_user = $user->clone();
Where the User model has
class User extends Eloquent {
public function roles() {
return $this->hasMany('Role', 'user_roles');
}
}
解决方案
tested in laravel 4.2 for belongsToMany relationships
if you're in the model:
//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);
}
这篇关于克隆一个雄辩的对象,包括所有的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文