codeigniter active records join with using?
I am wanting to write this query:
SELECT u.userId, uil.interestId, url.regionId FROM users u
JOIN userInterestLink uil USING (userId)
JOIN userRegionLink url USING (userId)
JOIN dealInterestLink dil USING (interestId)
JOIN dealRegionLink drl USING (regionId, dealId)
WHERE dealId = 1
using the code igniter active records class, howeve开发者_如何学Pythonr I have no ideda how to do the JOIN ... USING
There is no built-in support for JOIN ... USING
in the active record class. Your best bet would probably change the join()
function to be like this (the file is system/database/DB_active_rec.php
in case you don't know)
public function join($table, $cond, $type = '')
{
if ($type != '')
{
$type = strtoupper(trim($type));
if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER')))
{
$type = '';
}
else
{
$type .= ' ';
}
}
// Extract any aliases that might exist. We use this information
// in the _protect_identifiers to know whether to add a table prefix
$this->_track_aliases($table);
// Strip apart the condition and protect the identifiers
if (preg_match('/([\w\.]+)([\W\s]+)(.+)/', $cond, $match))
{
$match[1] = $this->_protect_identifiers($match[1]);
$match[3] = $this->_protect_identifiers($match[3]);
$cond = $match[1].$match[2].$match[3];
}
// Assemble the JOIN statement
$type.'JOIN '.$this->_protect_identifiers($table, TRUE, NULL, FALSE);
$using_match = preg_match('/using[ (]/i', $cond);
if ($using_match)
{
$join .= $cond;
}
else
{
$join .= ' ON '.$cond;
}
$this->ar_join[] = $join;
if ($this->ar_caching === TRUE)
{
$this->ar_cache_join[] = $join;
$this->ar_cache_exists[] = 'join';
}
return $this;
}
So then, you can simply use this in your code join('table', 'USING ("something")')
Although, you might want to extend the class instead of modifying it so that you won't need to do same thing over and over again when you upgrade your CI. Have a look at this article or this one (or search google) if you want to do so instead.
Or if you don't want to go all those troubles, you can write a simple helper function that can do the same thing.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function join_using($table, $key)
{
$CI = get_instance();
$join = 'JOIN '. $table .' USING (`'. $key .'`)';
return $CI->db->ar_join[] = $join;
}
Later on, just load the helper and call the function like this join_using('table', 'key')
. It will then produce the same result as you would with the original join()
except this one will give you USING
instead of ON
condition.
For example:
// $something1 and $something2 will produce the same result.
$something1 = $this->db->join('join_table', 'join_table.id = table.id')->get('table')->result();
print_r($something1);
join_using('join_table', 'id');
$something2 = $this->db->get('table')->result();
print_r($something2);
精彩评论