php - Lumen/Laravel - Eloquent:迁移 BIGINT 未签名为 PK 和 FK 的表
问题描述
我想迁移一个包含三个表的数据库:
Ad_users
广告组
Ad_usersxad_groups
后者显然是一个联结表,仅包含两个引用其他两个表的 PK 的 FK。现在,我有以下问题,这是 ad_users 表的迁移:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdusersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('Ad_users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('common_name');
$table->string('location');
$table->string('description');
$table->integer('postalcode');
$table->string('physical_delivery_office_name');
$table->string('telephone_number');
$table->string('initials');
$table->string('street_address');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Ad_users');
}
}
$table->bigIncrements('id');
创建一个 Columnbigint(20) unsigned
类型。包含 FK 的联结表中的列当然必须是完全相同的类型。但是,外键当然不能是联结表的主键,因此我不能使用$table->bigIncrements
语法,但 instad 必须使用$table->bigInteger
语法,如在 Ad_usersxad_groups 表的迁移中所示:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdusersxadgroupsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('Ad_usersxad_groups', function (Blueprint $table) {
$table->bigInteger('Ad_user_id');
$table->bigInteger('Ad_group_id');
$table->foreign('Ad_user_id')->references('id')->on('Ad_users');
$table->foreign('Ad_group_id')->references('id')->on('Ad_groups');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Ad_usersxad_groups');
}
}
出现的问题:
$table->bigInteger
创建一个类型的列bigint(20)
。这似乎与
bigint(20) unsigned
原始表的 PK 列中的类型不兼容。当我尝试运行迁移时,Artisan 引发以下错误:
SQLSTATE[HY000]: General error: 1005 Can't create table `aetherdb`.`ad_usersxad_groups` (errno: 150 "Foreign key constraint is incorrectly fo
rmed") (SQL: alter table `Ad_usersxad_groups` add constraint `ad_usersxad_groups_ad_user_id_foreign` foreign key (`Ad_user_id`) references `A
d_users` (`id`))
bigint(20) unsigned
除了从原始表的 PK 列上移开类型之外,还有什么方法可以解决这个问题?我可以以某种方式将其添加unsigned
到联结表中的非主键列吗?
解决方案
您可以使用$table->bigInteger('Ad_user_id')->unsigned();
使此 FK 无符号。
此功能称为列修饰符。您可以查看以下链接以获取列修饰符的完整列表。Laravel 数据库迁移 - 列修饰符
推荐阅读
- python - 我必须覆盖整数 __add__ 方法以支持整数和对象的加法吗?
- python - 重新绘制 2 个 pyplot 图表而不重新绘制新图表
- python - 如何使用 RSA 加密对超过 53 个字节的消息进行加密?
- bash - 如何从目录中创建的最新目录中复制文件?
- node.js - 为单个请求捕获多个路由
- docker - 在 docker 中运行 Localstack 时转发请求时出错
- php - 如何从同一个表中获取多个列
- laravel - How to orderBy Laravel Mutator value
- android - 为什么导航抽屉活动不起作用?
- c# - 如何下载文件电报机器人?