我添加了一些迁移来在laravel应用程序中构建SQL表。
表用户
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('user_id')->unique();
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
表用户列表
public function up()
{
Schema::create('userroles', function(Blueprint $table)
{
$table->foreign('user_id')->references('user_id')->on('users');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->timestamps();
});
}
但是当我运行它们时,我收到错误:
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'user_id' doesn't exist in table (SQL: alter table `userroles` add constraint userroles_user_id_foreign foreign key (`user_id`) references `users` (`user
_id`))
为什么?我认为用户表中的第二个条目是“user_id”,如预期的那样?这个专栏必须是PK吗?并且由于此列将GUID作为条目,是否适合将GUID用作PK?
答案 0 :(得分:2)
在userroles表中,您需要先设置密钥,然后再为外键设置密钥。
public function up()
{
Schema::create('userroles', function(Blueprint $table)
{
$table->string('user_id');
$table->unsignedInteger('role_id');
$table->foreign('user_id')->references('user_id')->on('users');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->timestamps();
});
}