【问题标题】:Implementing Composite Keys in CodeIgniter Models在 CodeIgniter 模型中实现复合键
【发布时间】:2021-03-02 16:13:08
【问题描述】:

有什么方法可以在 CodeIgniter 4 中使用 Models 实现复合主键?

像这样?

class SomeModel extends Model{
   
   protected $table      = 'table';
   protected $primaryKey1 = 'primary_composite_id1';
   protected $primaryKey2 = 'primary_composite_id2';
   protected $primaryKey3 = 'primary_composite_id3';

   // numbers in the identifiers were only added for clarity
   ...

}

我认为您可以使用Forge 类定义表结构。
这是我如何在 Migrations 中定义表的 sn-p。

SomeMigration.php

class SomeClass extends Migration{

    /* added fields here */
    ...
    
    // Set them as foreign keys
    $this->$forge->addForeignKey('item_id', 'item', 'item_id', 'CASCADE', 'CASCADE');
    $this->$forge->addForeignKey('poster_uid', 'user', 'user_id', 'CASCADE', 'CASCADE');
    $this->$forge->addForeignKey('customer_uid', 'user', 'user_id', 'CASCADE', 'CASCADE');


    // Set them as primary keys
    $this->$forge->addPrimaryKey('item_id');
    $this->$forge->addPrimaryKey('poster_uid');
    $this->$forge->addPrimaryKey('customer_uid');
    
    ...
}

另外,如果在Models 中设置复合主键是不可能的,我应该

  • 改为为该表创建一个新的主键列?
  • $primarykey 值留空并仅使用使用查询(例如使用WHERE)?
  • 使用表中任意一列(设置为PK)作为$primarykey的值?

问题是根据 Codeigniter MY_Model composite primary key 这个帖子创建的,因为答案没有直接回答问题

我目前正在为我们的学校项目使用该框架。文档中没有提到,所以我被卡住了。非常感谢任何一种替代解决方案。谢谢!干杯!

【问题讨论】:

    标签: codeigniter composite-primary-key codeigniter-4


    【解决方案1】:

    这些天我也遇到了同样的问题。 Codeigniter 似乎不支持模型主键的此功能。

    我在文档和 Model 的源代码中进行了搜索,发现它像处理一个值一样处理主键。 例如在模型查找方法中,我可以看到以下代码:

    $row = $builder->whereIn($this->table . '.' . $this->primaryKey, $id)

    在我的例子中,我将添加一个额外的 ID 列并将其用作主键。如果我以后找到更好的选择,我会在这里更新。

    最好的问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-12
      • 2017-06-12
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 2019-01-28
      • 1970-01-01
      相关资源
      最近更新 更多