【问题标题】:Clone an Eloquent object including all relationships?克隆一个包含所有关系的 Eloquent 对象?
【发布时间】:2014-07-16 16:52:30
【问题描述】:

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

例如,如果我有这些表:

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

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

类似这样的:

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

User 模型的位置

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

【问题讨论】:

    标签: laravel laravel-4 clone eloquent


    【解决方案1】:

    你可以试试这个(Object Cloning):

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

    由于clone 不进行深度复制,因此如果有任何子对象可用,则不会复制子对象,在这种情况下,您需要手动使用clone 复制子对象。例如:

    $user = User::with('role')->find(1);
    $new_user = clone $user; // copy the $user
    $new_user->role = clone $user->role; // copy the $user->role
    

    在您的情况下,roles 将是 Role 对象的集合,因此需要使用 clone 手动复制集合中的每个 Role object

    另外,您需要注意这一点,如果您不使用 with 加载 roles,那么这些将不会加载或在 $user 中不可用,以及何时调用$user->roles 然后这些对象将在调用 $user->roles 之后在运行时加载,在此之前,那些 roles 不会加载。

    更新:

    这个答案是针对 Larave-4 的,现在 Laravel 提供了 replicate() 方法,例如:

    $user = User::find(1);
    $newUser = $user->replicate();
    // ...
    

    【讨论】:

    • 小心,只有浅拷贝,而不是子/子对象:-)
    • @TheShiftExchange,你可以find it interesting,我很久以前做过一个实验。感谢您的赞许:-)
    • 这不也是复制对象的id吗?让它对储蓄毫无用处?
    • @Tosh,没错,这就是为什么你需要设置另一个 id 或 null :-)
    • plus1 用于揭示 php 的秘密:P
    【解决方案2】:

    你也可以试试 eloquent 提供的复制功能:

    http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_replicate

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

    【讨论】:

    • 实际上您还必须加载要复制的关系。给定的代码只会复制没有关系的基本模型。要克隆关系,您可以获取用户及其关系:$user = User::with('roles')->find(1); 或在拥有模型后加载它们:所以前两行将是 $user = User::find(1); $user->load('roles');
    • 加载关系似乎也不会复制关系,至少在 4.1 中不会。我必须复制父节点,然后遍历复制它们的原始子节点并一次更新它们以指向新的父节点。
    • replicate() 将设置关系,push() 递归到关系中并保存它们。
    • 同样在 5.2 中,您需要遍历孩子并在一次复制一个后保存它们;在 foreach 中:$new_user->roles()->save($oldRole->replicate)
    【解决方案3】:

    如果你有一个名为 $user 的集合,使用下面的代码,它会创建一个与旧集合相同的新集合,包括所有关系:

    $new_user = new \Illuminate\Database\Eloquent\Collection ( $user->all() );
    

    此代码适用于 laravel 5。

    【讨论】:

    • 你不能只做$new = $old->slice(0)吗?
    【解决方案4】:

    在 laravel 4.2 中测试了 belongsToMany 关系

    如果您在模型中:

        //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);
        }
    

    【讨论】:

    • 在 Laravel 7 中工作
    • 它也适用于以前版本的 Laravel 6。(我猜是基于之前的评论 :) )谢谢!
    • 在 Laravel 7.28.4 中工作。我注意到如果您尝试在模型之外运行代码,代码应该会有所不同。谢谢
    【解决方案5】:

    这是来自@sabrina-gelbart 的解决方案的更新版本,它将克隆所有 hasMany 关系,而不仅仅是她发布的 belongsToMany:

        //copy attributes from original model
        $newRecord = $original->replicate();
        // Reset any fields needed to connect to another parent, etc
        $newRecord->some_id = $otherParent->id;
        //save model before you recreate relations (so it has an id)
        $newRecord->push();
        //reset relations on EXISTING MODEL (this way you can control which ones will be loaded
        $original->relations = [];
        //load relations on EXISTING MODEL
        $original->load('somerelationship', 'anotherrelationship');
        //re-sync the child relationships
        $relations = $original->getRelations();
        foreach ($relations as $relation) {
            foreach ($relation as $relationRecord) {
                $newRelationship = $relationRecord->replicate();
                $newRelationship->some_parent_id = $newRecord->id;
                $newRelationship->push();
            }
        }
    

    【讨论】:

    • 如果some_parent_id 并非对所有关系都相同,则很棘手。不过这很有用,谢谢。
    【解决方案6】:

    对于 Laravel 5。用 hasMany 关系测试。

    $model = User::find($id);
    
    $model->load('invoices');
    
    $newModel = $model->replicate();
    $newModel->push();
    
    
    foreach($model->getRelations() as $relation => $items){
        foreach($items as $item){
            unset($item->id);
            $newModel->{$relation}()->create($item->toArray());
        }
    }
    

    【讨论】:

      【解决方案7】:

      如果其他解决方案不能让您满意,这里还有另一种方法:

      <?php
      /** @var \App\Models\Booking $booking */
      $booking = Booking::query()->with('segments.stops','billingItems','invoiceItems.applyTo')->findOrFail($id);
      
      $booking->id = null;
      $booking->exists = false;
      $booking->number = null;
      $booking->confirmed_date_utc = null;
      $booking->save();
      
      $now = CarbonDate::now($booking->company->timezone);
      
      foreach($booking->segments as $seg) {
          $seg->id = null;
          $seg->exists = false;
          $seg->booking_id = $booking->id;
          $seg->save();
      
          foreach($seg->stops as $stop) {
              $stop->id = null;
              $stop->exists = false;
              $stop->segment_id = $seg->id;
              $stop->save();
          }
      }
      
      foreach($booking->billingItems as $bi) {
          $bi->id = null;
          $bi->exists = false;
          $bi->booking_id = $booking->id;
          $bi->save();
      }
      
      $iiMap = [];
      
      foreach($booking->invoiceItems as $ii) {
          $oldId = $ii->id;
          $ii->id = null;
          $ii->exists = false;
          $ii->booking_id = $booking->id;
          $ii->save();
          $iiMap[$oldId] = $ii->id;
      }
      
      foreach($booking->invoiceItems as $ii) {
          $newIds = [];
          foreach($ii->applyTo as $at) {
              $newIds[] = $iiMap[$at->id];
          }
          $ii->applyTo()->sync($newIds);
      }
      

      诀窍是擦除 idexists 属性,以便 Laravel 创建一条新记录。

      克隆自我关系有点棘手,但我提供了一个示例。您只需创建旧 ID 到新 ID 的映射,然后重新同步。

      【讨论】:

        【解决方案8】:

        这是在 laravel 5.8 中,没有在旧版本中尝试过

        //# this will clone $eloquent and asign all $eloquent->$withoutProperties = null
        $cloned = $eloquent->cloneWithout(Array $withoutProperties)
        

        编辑,就在今天 2019 年 4 月 7 日laravel 5.8.10 launched

        现在可以使用复制

        $post = Post::find(1);
        $newPost = $post->replicate();
        $newPost->save();
        

        【讨论】:

          【解决方案9】:

          当您通过所需的任何关系获取对象并在此之后进行复制时,您检索到的所有关系也会被复制。例如:

          $oldUser = User::with('roles')->find(1);
          $newUser = $oldUser->replicate();
          

          【讨论】:

          • 我在 Laravel 5.5 中测试过
          【解决方案10】:

          这是一个递归复制对象上所有加载关系的特征。您可以轻松地将其扩展到其他关系类型,例如 Sabrina 的 belongsToMany 示例。

          trait DuplicateRelations
          {
              public static function duplicateRelations($from, $to)
              {
                  foreach ($from->relations as $relationName => $object){
                      if($object !== null) {
                          if ($object instanceof Collection) {
                              foreach ($object as $relation) {
                                  self::replication($relationName, $relation, $to);
                              }
                          } else {
                              self::replication($relationName, $object, $to);
                          }
                      }
                  }
              }
          
              private static function replication($name, $relation, $to)
              {
                  $newRelation = $relation->replicate();
                  $to->{$name}()->create($newRelation->toArray());
                  if($relation->relations !== null) {
                      self::duplicateRelations($relation, $to->{$name});
                  }
              }
          }
          

          用法:

          //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.nested_relation');
          
          // duplication all LOADED relations including nested.
          self::duplicateRelations($this, $new);
          

          【讨论】:

          • 如何更新上述复制枢轴关系的代码?
          猜你喜欢
          • 2019-02-26
          • 1970-01-01
          • 2015-08-27
          • 1970-01-01
          • 2014-10-01
          • 1970-01-01
          • 2020-11-01
          • 2014-07-17
          • 1970-01-01
          相关资源
          最近更新 更多