這是我最初的遷移
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->String('customer_name');
$table->String('customer_phone');
//others
});
現在,輕松的時間結束了,現在我必須將姓名和電話移至客戶表。這是我創建客戶遷移。我不知道在哪里做這個操作,所以我只是把所有的東西都放在了遷移中。
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('phone', 15);
//others
});
$users = DB::table('orders')->select(['customer_name', 'customer_phone'])->distinct()->get();
foreach ($users as $user) {
$attr['name'] = $user->customer_name;
$attr['phone'] = $user->customer_phone;
Customer::create($attr);
}
并更改順序遷移
Schema::table('orders', function (Blueprint $table) {
$table->unsignedBigInteger('customer_id')->nullable()->after('id');
$table->foreign('customer_id')->references('id')->on('customers');
});
現在我被空的customer_id困住了。我不知道下一步該做什么,除了通過參考兩個表手動插入它,這可能需要太多時間來更新數百行。
uj5u.com熱心網友回復:
嘗試在 up 函式上使用此陳述句。
DB::statement("UPDATE `orders` o SET `customer_id` = (SELECT `id` FROM `customers` WHERE `name` = o.customer_name AND `phone` = o.customer_phone)");
您可能想洗掉這兩列。這個也扔。
Schema::table('orders', function (Blueprint $table) {
$table->dropColumn(['customer_name', 'customer_phone']);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/416429.html
標籤:
