【问题标题】:Laravel: Copy models/rows from one connection to anotherLaravel:将模型/行从一个连接复制到另一个
【发布时间】:2019-06-28 01:53:22
【问题描述】:

我想将一个 eloquent 模型从一个连接复制到另一个连接。

到目前为止,我这样做的方式是这样的:

$users = User::on('connection1')->where('tenant', 'foo')->get();
User::on('connection2')->insert($users->toArray());

这在大多数情况下都有效。但在某些情况下,这不起作用。例如:

  • 当模型有$hidden属性时
  • 当模型的 toArray 方法被覆盖时

简单地将某些行复制到另一个连接的可靠方法是什么?

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-5.7


    【解决方案1】:

    我想我已经找到了 $hidden 属性和覆盖 toArray 方法的解决方案

     $users = User::on('connection1')->where('tenant', 'foo')->get();
    
    foreach ($users as $user) {
                $usersArray[] = $user->getAttributes();
            }
    User::on('connection2')->insert($usersArray);
    

    如果您使用的是 mySql,我建议您使用批量插入:

    https://www.geeksengine.com/database/data-manipulation/bulk-insert.php

    【讨论】:

      【解决方案2】:

      您可以像这样在 eloquent 模型上利用 setConection() 方法:

      $users = User::on('connection1')->where('tenant', 'foo')->get();
      foreach ($users as $user) {
         $user->setConnection('connection2');
         $user->save();
      }
      

      我在另一个 stackoverflow 问题 here 中找到了这个

      【讨论】:

      • 如果在执行save 方法之前用户在connection2 上不存在,此解决方案将失败
      • 可以在save()前添加$user->exists = false;,创建一个不存在的用户
      猜你喜欢
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 2017-04-24
      • 2019-02-18
      相关资源
      最近更新 更多