我试图在一次迁移中用主键创建外键。
这是针对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”作为主键构成一个普通表,但它不是外键。
答案 0 :(得分:0)
尝试此代码
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();
});
答案 1 :(得分:0)
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');
});
答案 2 :(得分:0)
<?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');
}
}
现在,您想要在foriegn key
表中的users
表中将teachers
设置为 id
我已清除
现在 将列添加到techers表并添加foriegn键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
希望有帮助
答案 3 :(得分:0)
您尝试过吗?
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()
那样链接到列定义上。