如何使用Laravel 7从两个不同的连接将select语句插入MySql数据库



我正试图将数据从一个数据库复制到另一台服务器上的另一个数据库。这些数据库结构相同。通过四处搜索,我尝试过在Laravel中使用insertUsing((方法。

$new_connection = DB::connection('mysql2');
//Insert Using requires an array of columns
$column_list = Schema::getColumnListing('users');
//This is my select statement
$select = $new_connection->table('users')->select('*');
//This is my insert statement
DB::table('users')->insertUsing($column_list,$select);

这不会产生任何错误,但没有数据被插入到表中。如果我在复制到的数据库中有相同的数据,我会收到一个错误,说主键已经存在,所以我知道它正在从另一台服务器读取数据。

有其他方法可以完成吗?

insertUsing使用的子查询将无法使用单独的数据库。没有潜在的限制,只是Laravel在构建查询时不使用数据库前缀。因此,如果你的数据库在同一台服务器上,你可以通过构建这样的原始查询来做到这一点:

DB::insert("INSERT INTO mysql1.users SELECT * FROM mysql2.users");

另一种选择是从一个数据库中提取数据并将其插入另一个数据库。假设您有一个相当大的表,您应该使用分块来确保不会将整个表加载到内存中。

如果您正从";mysql2";连接到您的默认连接它可能看起来像这样:

$users1 = DB::table('users');
$users2 = DB::connection('mysql2')->table('users');
$page = 0;
$size = 50;
while (true) {
// get some records
$users = $users2->skip($page * $size)->take($size)->get();
// end the loop when there are no more results
if ($users->count() === 0) {
break;
}
// convert the results and each row to an array
$user_array = $users->map(fn ($u) => (array)$u)->toArray();
// save them into the new database
$users1->insert($user_array);
// increment the page for the next iteration
$page++;
}

不过,我建议使用适当的工具,如mysqldump来完成此操作。

最新更新