当使用或迁移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/DatabaseExceptions/DatabaseException CodeIgniter/Database/Exceptions/DatabaseException消息。 字段
categories_id
未找到。
这段代码的问题是,在调用
$this->forge->createTable('products');
它将重置查询对象,所以它将失去对表的引用,并且不会找到你正在寻找的特定字段。所以像这样改变你的查询顺序。
$this->forge->addForeignKey('categories_id', 'categories', 'id');
$this->forge->createTable('products');
谢谢你的回答,我已经尝试过这样做了,但还是出现了错误,正确的做法(后来我设法解决了)是这样生成category_id字段,然后按你说的方式进行调用
'categories_id' => ['type' => 'INT',
'unsigned' => TRUE]
$this->forge->addForeignKey('categories_id', 'categories', 'id');
$this->forge->createTable('products');
谢谢大家