从一个数据库读取并写入另一个 php/laravel


Read from one database and write to another php/laravel

我正在学习Laravel,并且知道如何从数据库读取数据并将其自动写入第二个数据库。

首先,我从 db1 读取,它可以工作:

$paciente_q = Pacientes::on('db1')->find($id);

然后我希望将数据移动到 db2 上的相同表(在配置中分配)

Pacientes::create($paciente_q);

错误是我传递了一个对象,而"::create"想要一个数组。我将其转换为数组,但没有工作。我能找到的唯一选择是用数据创建一个数组,然后制作 ::create。但我认为应该有一个更简单的方法。我说的是 10 列。

如果我们谈论数百列,我该怎么办?

您的方法不起作用可能是因为出于安全原因,默认情况下阻止了批量分配; 您需要在模型的 fillable 属性(应该是数组)中手动设置可批量分配的模型字段 - 如果您不关心这种安全性,或者确定您永远不会直接将用户输入批量分配给您的模型,您可以通过设置 guarded 属性使所有字段可批量分配的模型到空数组。

完成后,您的代码基本上是正确的,只需将模型转换为数组,并且不要忘记在创建模型时选择第二个数据库,如下所示:

// the model to insert, converted to an array - get() would also work but first() ensures we get only one record even if the primary key is messed up and there are multiple values with the same ID
$paciente_q = Pacientes::on("db1")->find($id)->first()->toArray();
// create the same model on the second database
Pacientes::on("db2")->create($paciente_q);

现在,如果您想偶尔对几行执行此操作,那么上述方法是合适的,否则您可以查看批量插入,下面是将整个表从第一个数据库复制到第二个数据库的示例:

// an array with all the rows
$patients = Pacientes::on("db1")->all()->toArray();
// get the model's table name
$table = with(new Pacientes)->getTable(); 
// bulk insert all these rows into the second database
DB::connection("db2")->table($table)->insert($patients);

请注意,这里我们不使用 Eloquent 来插入它们,因此我们必须首先从模型的实例中获取表的名称;如果第二个数据库上的表名称与第一个数据库不同,则相应地调整$table变量。

解决方案是将 get() 更改为 first(),因为我们正在寻找一个项目。我从@André中读错了第一个解决方案...不好意思!应该学习阅读而不是拉拉维尔!

$paciente_q = Pacientes::on('db1')->where('numerohistoria',$numerohistoria)->first()->toArray();
    Pacientes::create($paciente_q);

现在它工作了!!感谢大家,特别是@André!