[英]Laravel 5 - Add column and foreign key to an existing table with data
我是 Laravel 的新手! 但我正在努力。 這是我可以使用的一些幫助;
我有一個帖子表。 我有一個用戶表。 但是我忘了在鏈接到用戶 ID 的帖子表中添加外鍵。
create users 表遷移:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
創建帖子表遷移:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
我已經創建了新的遷移文件:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterTablePostsAddForeignUser extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
// I HAVE NO IDEA WHAT TO DO NEXT
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
我不知道如何填寫這里的“public function up()”方法! 如果有人可以幫忙! 將不勝感激!
我試過這個,這對我有用。
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->nullable()->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
這里當您添加外鍵時,默認情況下它將具有 Null 值。此“空引用”可能會導致問題。 使用nullable()
外鍵可以避免這個問題。
請參閱此處的文檔
您需要在修改列之前安裝doctraine/dbal
,請務必在您的 composer.json 文件中添加學說/dbal 依賴項。 Doctrine DBAL 庫用於確定列的當前狀態並創建對列進行指定調整所需的 SQL 查詢,您應該嘗試我在這篇SO 帖子中找到的內容
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->change();
$table->foreign('user_id')->references('id')->on('users');
});
change()
列結構的change()
方法
在此之后運行工匠命令
php artisan migrate
如果這對您不起作用,請在此處發表評論! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.