2014-11-17 137 views
0

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

首先,我从DB1读取和它的工作原理:

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

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

Pacientes::create($paciente_q); 

的错误是我传递一个对象,“:: create”想要一个数组。我将它转换为一个数组,但没有奏效。我能找到的唯一选择是用数据创建一个数组,然后创建:: create。但我认为应该有一个更简单的方法。我在谈论10栏。如果我们谈论数百个专栏,我该怎么办?

谢谢! 禁令。

+0

为什么转换为数组不工作?你有错误吗? – lukasgeiter

+0

你只是想复制表?使用SQL而不是雄辩。或者展示使用雄辩的理由。 –

+0

我需要从db1读取数据,如果这个数据在db2中不存在,那么应用程序应该将它写入db2。我使用两个数据库。一个只有阅读烫发,第二个是我们可以写的。 –

回答

2

您的方法不起作用可能是因为默认情况下mass assignment出于安全原因被阻止;您需要手动设置模型的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); 

现在,如果你要做到这一点偶尔几行,那么上面的方法是正确的,否则你可以看bulk insertion,这里是从第一个数据库复制整个表,第二个例子:

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

注意的是,这里我们没有使用雄辩f或者插入它们,所以我们必须首先从模型的一个实例中获取表名;如果第二个数据库中的表名与第一个不同,则相应地调整$table变量。

+0

我会告诉你的! ;-) –

+0

试过你的第一个解决方案,并得到错误:参数1传递给Illuminate \ Database \ Eloquent \ Model :: create()必须是在/ var/www/bg-dental/app中调用的类型数组, /controllers/PresupuestosController.php第47行并定义... 我没有指定第二个数据库,因为它是配置中的第一个数据库。 –

+0

哦!等待!我忘了toArray()....哎呀...! –

1

解决方法是将get()更改为first(),因为我们正在搜索一个项目。我错看了@André的第一个解决方案......对不起!应该学习阅读而不是Laravel!

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

    Pacientes::create($paciente_q); 

现在它的工作原理!感谢所有人,并特别感谢@André!

相关问题