2011-09-11 13 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 

をしかし、私はどのようにJOIN ... USING

答えて

3

を行うにはidedaがされていない無組み込みサポートでJOIN ... USINGのためにアクティブレコードクラス。あなたの最善の策は、おそらく(ファイルが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()機能を変更しますjoin('table', 'USING ("something")')

が、 CIをアップグレードするときに同じことを何度も繰り返す必要がないように、クラスを変更する代わりにクラスを拡張することができます。 代わりにそうしたい場合はarticleまたはthis one(またはGoogle検索)をご覧ください。

これらの問題をすべて解決したくない場合は、同じことができる簡単なヘルパー関数を作成できます。

<?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()と同じ結果を生み出しますが、ONの代わりにUSINGが与えられます。例えば

// $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); 
関連する問題