我做了两个迁移表用户角色和用户。当我迁移它。它说成功完成他们两个,但只有用户表是在数据库中没有用户角色。虽然数据库已经创建了role_id作为外键,但没有用户角色表在数据库中。
整体图片
迁移表
下面是我的迁移代码
用户角色
<?php namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class UserRoles extends Migration
{
public function up()
{
$this->forge->addField([
'role_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true
],
'role' => [
'type' => 'VARCHAR',
'constraint' => 255
],
'role_description' => [
'type' => 'TEXT',
'null' => true
],
'created_at' => [
'type' => 'timestamp',
'default' => 'current_timestamp'
],
'created_by' => [
'type' => 'int',
'constraint' => 11,
'null' => true
],
'updated_at' => [
'type' => 'timestamp',
'null' => true
],
'updated_by' => [
'type' => 'int',
'constraint' => 11,
'null' => true
],
'deleted_at' => [
'type' => 'timestamp',
'null' => true
],
]);
$this->forge->addKey('role_id', true);
$this->forge->createTable('user_roles');
}
//--------------------------------------------------------------------
public function down()
{
$this->forge->dropTable('user_roles');
}
}
用户迁移代码
<?php namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Users extends Migration
{
public function up()
{
$this->db->disableForeignKeyChecks();
$this->forge->addField([
'user_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true
],
'first_name' => [
'type' => 'VARCHAR',
'constraint' => 255
],
'last_name' => [
'type' => 'VARCHAR',
'constraint' => 255
],
'email' => [
'type' => 'VARCHAR',
'constraint' => 255
],
'password' => [
'type' => 'VARCHAR',
'constraint' => 255
],
'role_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'transaction_pin' => [
'type' => 'VARCHAR',
'constraint' => 255
],
'created_by' => [
'type' => 'int',
'constraint' => 11,
'null' => true
],
'updated_at' => [
'type' => 'timestamp',
'null' => true
],
'updated_by' => [
'type' => 'int',
'constraint' => 11,
'null' => true
],
'deleted_at' => [
'type' => 'timestamp',
'null' => true
],
]);
$this->forge->addKey('user_id', true);
$this->forge->addForeignKey('role_id', 'user_roles', 'role_id', 'cascade', 'null');
$this->forge->createTable('users');
$this->db->enableForeignKeyChecks();
}
//--------------------------------------------------------------------
public function down()
{
$this->db->disableForeignKeyChecks();
$this->forge->dropTable('user_id');
$this->db->enableForeignKeyChecks();
}
}
有人能帮我一下吗
4条答案
按热度按时间zkure5ic1#
我遇到过同样的问题。这是因为migrate试图在
users
表之前创建user_roles
表,并且无法添加外键,因为user_roles
表不存在。我建议您在迁移user_roles
表之后迁移users
表。可以使用以下命令单独迁移迁移类:
文档为here。
pu3pd22g2#
你可能会因为type =〉timestamp而遇到这个问题。尝试不带字段(updated_at和deleted_at)。我也遇到了同样的问题。
rqmkfv5c3#
指定数据库连接。
并确保你在app/config/database.php中处于默认连接
tktrz96b4#
您只需使用特定的迁移类名:
同时检查:https://codeigniter4.github.io/CodeIgniter4/cli/cli_commands.html