Adding table prefix to join in Codeigniter

2019-02-20 20:38发布

问题:

I have Codeigniter setup to add the prefix kms_ to my active record queries. However, I am trying to do a join with two ON conditions and it doesn't prepend them.

Right now I have to manually add them like so:

$this->db->join('site_items', 'kms_site_items.item_id = kms_items.id AND kms_site_items.site_id = 1', 'left');

Can I write this differently so that the table prefixes are added correctly?

Is there a way to get something like this to work:

$this->db->join('site_items', 'site_items.item_id = items.id AND site_items.site_id = 1', 'left');

回答1:

You can get the current database prefix manually like this:

$prefixed_tablename = $this->db->dbprefix('tablename');

So you could do this:

$this->db->join('site_items', $this->db->dbprefix('site_items') . '.item_id = ' . $this->db->dbprefix('items') . '.id AND ' . $this->db->dbprefix('site_items') . '.site_id = 1', 'left');

Docs Here



回答2:

You can simply add Prefix table name like this :
for example your tables have myPrefix_ as prefix and one of them might be myprefix_user.
After that in your config/database.php at the bottom of this page where you set your database name, username and password, You can see dbprefix and you can set your prefix as I mentioned above myPrefix_.
At the end, You can simply call your table name for example $this->db->get('user') and automatically Codeigniter set your prefix at the first of it.