Codeigniter MY_Model 复合主键 [英] Codeigniter MY_Model composite primary key

查看:89
本文介绍了Codeigniter MY_Model 复合主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基类 MY_Model 来访问包含所有 CRUD 方法的数据库.我使用的模型是 Jens Segers 的 MY_Model:

I'm working with a base class MY_Model for accessing the database, which contains all the CRUD methods. The model which I'm using is Jens Segers' MY_Model:

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

现在,我的数据库中有一个表,其中包含一个复合主键(article_id 和 tag_id).通常,当主键仅包含一个 ID 时,我可以使用:

Now, I have a table in my database which contains a composite primary key (article_id and tag_id). Normally, when the primary key contains only an ID for instance, I could just use:

protected $primary_key = "id";

是否有可能使用复合主键,还是应该添加一个列 ID 作为唯一的主键?

Is there a possibility for a composite primary key, or should I add a column ID to be the only primary key?

提前致谢.

推荐答案

不要牺牲您的数据库结构,因为您使用的自定义库并不完全支持您的需求.

Don't sacrifice your database structure because the custom library you are using doesn't support exactly what you need.

不过有一个解决办法:

该库使用 CI 的数据库库并使用 db->where() 函数中的 $primary_key.

That library uses CI's database library and uses the $primary_key in the db->where() function.

该函数接受以下参数格式:

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");

因为库不断使用上面where()方法的第一个方法.

as the library constantly uses the first method of the where() method above.

相反,只需每次使用 array("article_id" => $article_id) 提供像 get()insert()(或其他)这样的方法, "tag_id => tag_id).

Instead, just supply methods like get() or insert() (or other) each time with array("article_id" => $article_id, "tag_id => tag_id).

如果您尝试插入与您的主键匹配的任何内容,数据库将抛出错误,因此您可以处理该问题.

The database will throw an error if you try and insert anything matching your primary key, so you can deal with that then.

这篇关于Codeigniter MY_Model 复合主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆