我开始使用Laravel进行一个小项目,我想创建客户端组织表,就像一个用户可以拥有一个或多个组织一样。
但是运行迁移命令后,我收到一条错误消息:
public function up()
{
Schema::create('client_organizations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('organization_id');
$table->foreign('organization_id')->references('id')->on('organizations');
$table->timestamps();
});
}
组织表:
public function up()
{
Schema::create('organizations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('organization_name');
$table->string('phone');
$table->string('fax');
$table->string('address');
$table->string('city');
$table->string('zipcode');
$table->string('website');
$table->string('linkedin');
$table->string('facebook');
$table->string('twitter');
$table->timestamps();
});
}
我得到的错误:
SQLSTATE[HY000]: General error: 1005 Can't create table `cms`.`client_organi
zations` (errno: 150 "Foreign key constraint is incorrectly formed")
答案 0 :(得分:0)
client_organizations
属于organizations
,所以您需要先创建organizations
表,然后再创建client_organizations
。
Laravel 5.8添加了bigInteger
作为外键的默认值。
组织
public function up()
{
Schema::create('organizations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('organization_name');
$table->string('phone');
$table->string('fax');
$table->string('address');
$table->string('city');
$table->string('zipcode');
$table->string('website');
$table->string('linkedin');
$table->string('facebook');
$table->string('twitter');
$table->timestamps();
});
}
client_organizations
public function up()
{
Schema::create('client_organizations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->bigInteger('organization_id')->unsigned();
$table->foreign('organization_id')->references('id')->on('organizations');
$table->timestamps();
});
}