我正在嘗試將資料從一個資料庫復制到另一臺服務器上的另一個資料庫。資料庫在結構上是相同的。通過四處搜索,我嘗試使用 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);
這不會產生任何錯誤,但不會將資料插入表中。如果我要復制到的資料庫中有相同的資料,我會收到一條錯誤訊息,指出主鍵已經存在,所以我知道它正在從另一臺服務器讀取資料。
還有其他方法可以完成這項作業嗎?
uj5u.com熱心網友回復:
諸如 by 使用的子查詢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來執行此操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411090.html
標籤:
