[英]Cannot make a primary key and foreing key at the same time with migration Laravel
我試圖在一次遷移時在主鍵中創建一個外鍵。
這適用於 Laravel 5.7。 我嘗試了不同的方法來嘗試實現我的目標。 這是我的最終代碼。
Schema::create('teachers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('user_id')->unsigned()->primary();
$table->timestamps();
});
Schema::table('teachers', function($table) {
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
它制作了一個以“user_id”為主鍵的普通表,但它不是外鍵。
試試這個代碼
Schema::create('teachers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
Schema::create('teachers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('user_id')->unsigned()->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
});
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTeachersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('teachers'))
{
Schema::create('teachers', function (Blueprint $table) {
$table->increments('id');
$table->string('teacher_name');
$table->unsignedInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('teachers');
}
}
現在你想在teachers
表中設置作為users
表的id的外foriegn key
我清楚嗎
現在將列添加到 techers 表並添加外鍵 constarint
METHOD ONE
添加列
$table->unsignedInteger('user_id');
添加主鍵
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
現在解釋user_id
是教師表中的字段名稱references('id')
正在引用 id on('users')
在用戶表上
METHOD TWO
添加列
$table->integer('user_id');
添加主鍵
$table->foreign('user_id')->references('id')->on('users')->unsigned()->onDelete('cascade');
釋現在user_id
在教師表中的字段名references('id')
被引用id on('users')
是用戶表, unsigned()
將unsignedinteger
列
If Your issue is not solved kindly comment below
希望能幫助到你
你試過這個嗎?
Schema::create('teachers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->primary('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
我不認為primary()
可以像unique()
那樣鏈接到列定義上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.