简体   繁体   English

Laravel UUID为主键,ID为外键

[英]Laravel UUID as primary key and ID as foreign key

I've defined a uuid as primary key, and would like to use id (auto increment) as foreign key to define relationships.我已将uuid定义为主键,并希望使用id (自动增量)作为外键来定义关系。

Both Posts and Comments have in their migration:帖子和评论都在迁移中:

$table->uuid('uuid')->primary();
$table->bigInteger('id');

Their models have:他们的模型有:

protected $primaryKey = 'uuid';
protected $keyType = 'string';
public $incrementing = false;

And the comments migration has并且评论迁移有

$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

But if I run the migration I get General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_post_id_foreign` foreign key (`post_id`) references `posts` (`id`) on delete cascade) of which I'm not sure why it's happening?但是,如果我运行迁移,我会收到General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_post_id_foreign` foreign key (`post_id`) references `posts` (`id`) on delete cascade)其中我不确定为什么会这样? Before adding the UUID logic it was working fine so I'm sure I've made a mistake there, but I'm not sure what as the error is generic.在添加 UUID 逻辑之前它工作正常,所以我确定我在那里犯了一个错误,但我不确定这个错误是通用的。

Adding a foreign key requires the referenced key and the foreign one to have the same type and sign.添加外键需要引用的键和外键具有相同的类型和符号。 According to your migrations, both posts.id and comments.id are signed bigints but you are trying to add a foreign key to a un signed bigint.根据您的迁移, posts.idcomments.id都是已签名的 bigint,但您正在尝试将外键添加到签名的 bigint。

In your migrations for posts and comments , change在您的postscomments迁移中,更改

$table->bigInteger('id');

to

$table->bigInteger('id')->unsigned();

and migrate them again.并再次迁移它们。

Give this a try.试试这个。

$table->foreignId('post_id')->constrained('posts')->onDelete('cascade');

You can try this.你可以试试这个。

$table->foreignUuid('post_id')->constrained()->onDelete('cascade');

You can have a look at the method which is inside the vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php您可以查看 vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php 中的方法

 /**
 * Create a new UUID column on the table with a foreign key constraint.
 *
 * @param  string  $column
 * @return \Illuminate\Database\Schema\ForeignIdColumnDefinition
 */
public function foreignUuid($column)
{
    return $this->columns[] = new ForeignIdColumnDefinition($this, [
        'type' => 'uuid',
        'name' => $column,
    ]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM