你如何在 Laravel 4 中使用 BIGINT 作为自动递增的主键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17904819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you use a BIGINT as an Auto-Incrementing Primary Key in Laravel 4
提问by reikyoushin
I am trying to mimic wordpress' primary key sizewhich is BIGINT(20) but it seems that laravel doesn't have a native function to do this.. I saw a page in the laravel forumsand got a code like this:
我试图模仿WordPress的主键的尺寸是BIGINT(20),但它似乎laravel没有一个本地函数来做到这一点。我看到了一个在laravel论坛页面,并得到了这样的代码:
$table->bigInteger('id')->primary();
$table->bigInteger('id')->primary();
but when i try to attach a foreign key to that id during artisan migrate
, there is a MYSQL error that is thrown:
但是当我尝试在 期间将外键附加到该 id 时artisan migrate
,会抛出一个 MYSQL 错误:
[Exception] SQLSTATE[HY000]: General error: 1005 Can't create table 'db.#sql- 1730_15' (errno: 150) (SQL: alter table
users
add constraint users_role_id_foreign foreign key (role_id
) referencesroles
(id
)) (Bindings: array ( ))
[异常] SQLSTATE[HY000]: 一般错误: 1005 无法创建表 'db.#sql-1730_15' (errno: 150) (SQL: alter table
users
add constraint users_role_id_foreign Foreign key (role_id
) referencesroles
(id
)) (Bindings: array ( ))
What is the proper way to do this or where do i get this thing wrong?
这样做的正确方法是什么,或者我在哪里弄错了这件事?
thanks!
谢谢!
回答by rmobis
You most likely forgot to also set the type of your role_id foreign key as BIGINT(20) as well. This isn't really a Laravel issue, but rather MySQL's.
您很可能忘记将您的 role_id 外键的类型也设置为 BIGINT(20) 。这实际上不是 Laravel 的问题,而是 MySQL 的问题。
By the way, Laravel does have a native function to do this:
顺便说一句,Laravel 确实有一个原生函数可以做到这一点:
$this->bigIncrements('id');
This takes care of making it unsigned, auto incrementand primary key.
这负责使它成为unsigned,auto increment和primary key。
回答by Vipertecpro
When using bigInteger() also applying it to foreign key in some table, make sure you connect it properly with unsignedBigInteger(),
当使用 bigInteger() 也将其应用于某个表中的外键时,请确保将其与 unsignedBigInteger() 正确连接,
public function up()
{
Schema::create('create_this_table_after_users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
// Other Columns
});
Schema::table('create_this_table_after_users', function($table) {
$table->foreign('user_id')->references('id')->on('users');
// Other Constraints
});
}