2011-09-11 72 views
2

我想写这个查询:使用的代码点火器活动记录类codeigniter活动记录加入使用?

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 

,但是我没有ideda怎么办JOIN ... USING

回答

3

有没有内置支持在JOIN ... USING活跃的记录类。你最好的选择可能会改变join()功能是这样的(该文件是system/database/DB_active_rec.php如果你不知道)

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; 
} 

那么,你可以简单地在你的代码中使用此join('table', 'USING ("something")')

虽然,您可能需要扩展该类而不是修改它,以便在升级CI时不需要一遍又一遍地重复执行相同的操作。 看看这articlethis one(或谷歌搜索),如果你想这样做,而不是。或者,如果你不想遇到所有这些麻烦,你可以写一个简单的助手函数来完成同样的事情。

<?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; 
} 

稍后,只需加载助手并调用像这样的函数join_using('table', 'key')。然后它会产生与原始join()相同的结果,除了这一个将给你USING而不是ON条件。

例如:

// $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);