简体   繁体   English

Codeigniter MY_Model复合主键

[英]Codeigniter MY_Model composite primary key

I'm working with a base class MY_Model for accessing the database, which contains all the CRUD methods. 我正在使用基类MY_Model来访问数据库,该数据库包含所有CRUD方法。 The model which I'm using is Jens Segers' MY_Model: 我使用的模型是Jens Segers的MY_Model:

https://github.com/jenssegers/CodeIgniter-My-Model https://github.com/jenssegers/CodeIgniter-My-Model

Now, I have a table in my database which contains a composite primary key (article_id and tag_id). 现在,我的数据库中有一个包含复合主键(article_id和tag_id)的表。 Normally, when the primary key contains only an ID for instance, I could just use: 通常,当主键只包含一个ID时,我可以使用:

protected $primary_key = "id";

Is there a possibility for a composite primary key, or should I add a column ID to be the only primary key? 是否有可能使用复合主键,还是应该添加列ID作为唯一的主键?

Thanks in advance. 提前致谢。

Don't sacrifice your database structure because the custom library you are using doesn't support exactly what you need. 不要牺牲您的数据库结构,因为您使用的自定义库并不完全支持您所需的。

There's a work around however: 然而,有一个工作:

That library uses CI's database library and uses the $primary_key in the db->where() function. 该库使用CI的数据库库,并使用db->where()函数中的$primary_key

That function accepts the following argument formats: 该函数接受以下参数格式:

$this->db->where('name', $name);
$this->db->where($array);
$this->db->where($where);//$where is a custom MySQL query string

Therefore, you CANNOT set a composite primary key by setting: 因此,您无法通过设置来设置复合主键:

$primary_key = array("article_id", "tag_id");

as the library constantly uses the first method of the where() method above. 因为库不断使用上面where()方法的第一种方法。

Instead, just supply methods like get() or insert() (or other) each time with array("article_id" => $article_id, "tag_id => tag_id) . 相反,每次只使用array("article_id" => $article_id, "tag_id => tag_id)提供get()insert() (或其他)等方法。

The database will throw an error if you try and insert anything matching your primary key, so you can deal with that then. 如果您尝试插入与主键匹配的任何内容,数据库将抛出错误,因此您可以处理该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM