您的方法不起作用可能是因为默认情况下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
变量。
为什么转换为数组不工作?你有错误吗? – lukasgeiter
你只是想复制表?使用SQL而不是雄辩。或者展示使用雄辩的理由。 –
我需要从db1读取数据,如果这个数据在db2中不存在,那么应用程序应该将它写入db2。我使用两个数据库。一个只有阅读烫发,第二个是我们可以写的。 –