簡體   English   中英

Forge Migrate CodeIgniter 4 外鍵錯誤

[英]Forge Migrate CodeIgniter 4 Foreign Key Error

使用或遷移Codeigniter生成關系時出現如下代碼或錯誤

遷移產品

public function up()
{

    $this->forge->addField([
        'id'            => [
            'type'           => 'INT',
            'unsigned'       => TRUE,
            'auto_increment' => TRUE
        ],
        'categories_id' => [
            'type'          => 'INT'
        ],
        'product'       => [
            'type'          => 'VARCHAR',
            'constraint'    => '255'
        ]
    ]);
    $this->forge->addKey('id', TRUE);
    $this->forge->createTable('products');
    $this->forge->addForeignKey('categories_id', 'categories', 'id');

}

遷移類別

$this->forge->addField([
        'id'            => [
            'type'           => 'INT',
            'unsigned'       => TRUE,
            'auto_increment' => TRUE
        ],
        'category'      => [
            'type'          => 'VARCHAR',
            'constraint'    => '255'
        ],
        'ordination'    => [
            'type'          => 'INTEGER'
        ],
        'isactive'      => [
            'type'          => 'INTEGER',
            'default'       => 1
        ]
    ]);

    $this->forge->addKey('id', TRUE);
    $this->forge->createTable('categories');

錯誤

類型:CodeIgniter\Database\Exceptions\DatabaseException 消息:未找到字段categories_id

這段代碼的問題是在調用之后

$this->forge->createTable('products');

它將重置查詢 object,因此它將丟失對表的引用,並且不會找到您要查找的特定字段。 因此,像這樣更改查詢的順序:

$this->forge->addForeignKey('categories_id', 'categories', 'id');
$this->forge->createTable('products');

感謝您的回答,我已經嘗試過這樣做,但是仍然報錯,正確的事情(后來我設法解決了)是以這種方式生成 categories_id 字段並按照您提到的方式進行調用

'categories_id' => ['type' => 'INT',
                    'unsigned' => TRUE]

$this->forge->addForeignKey('categories_id', 'categories', 'id');
$this->forge->createTable('products');

謝謝你們

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM