[英]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.