从一个数据库复制到另一个数据库

从一个数据库复制到另一个数据库

本文介绍了Laravel 4.2:将数据库记录从一个数据库复制到另一个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Laravel 4.2中将记录的子集从一个数据库复制到另一个数据库

I need to copy a subset of records from one database to another in Laravel 4.2

我编写了一个工匠任务,该任务从默认"数据库连接中加载我需要复制的模型,现在需要将它们保存到第二个数据库连接(在config/database.php中定义).我找不到使用模型的save()方法保存到数据库(默认连接除外)的任何方法.

I've written an artisan task that loads the models that I need to copy from the "default" database connection, and now need to save them to the second database connection (which is defined in config/database.php). What I can't find is any way to use the model's save() method to save to a database other than the default connection.

这可能吗?我可以将保存推送"到第二个数据库连接吗?还是我需要更改为拉"逻辑,反转数据库连接定义,并从第二"连接加载数据,然后再保存为默认"?

Is this possible? Can I "push" my saves to the second database connection? Or do I need to change to a "pull" logic, reverse my database connection definitions, and load the data from the "second" connection before saving to the "default"?

推荐答案

如@Filip所示,必须在保存模型之前将模型上的连接设置为第二个(目标)数据库.

As @Filip has indicated, it's necessary to set the connection on the model to the second (destination) database before saving the model.

但是,还必须将 id 设置为null(除非您确定第二个数据库中不存在具有该id的记录,但我不能),以确保新的增量id值将被分配.

However, it's also necessary to set the id to null (unless you are certain that no record with that id exists on the second database, which I couldn't) to ensure that a new incrementing id value will be allocated.

保存之前,还必须将模型的 exists 属性设置为 false .从源数据库读取记录后,该值在模型中为 true ,因为从那里成功读取了记录(而不是将记录创建为新记录).未能重置 exists 导致Laravel尝试执行 UPDATE WHERE id = $ model-> id ,该操作不会向数据库写入任何内容,因为没有匹配记录(具有空ID)以进行更新.将 exists 设置为 false 可确保保存以 INSERT 执行.

And its also necessary to set the exists property of the model to false before saving. This value is true in the model after reading the record from the source database, because the record was successfully read from there (rather than being created as a new record). Failing to reset exists resulted in Laravel trying to execute an UPDATE WHERE id = $model->id, which wouldn't write anything to the database, because there was no matching record (with a null id) to update. Setting exists to false ensures that the save executes as an INSERT.

这篇关于Laravel 4.2:将数据库记录从一个数据库复制到另一个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:40