2013-04-18 38 views
0

我有一個codeigniter應用程序。codeigniter將複雜查詢變爲活動記錄

我的活動記錄語法完美的作品是:

function get_as_09($q){ 
    $this->db->select('m3'); 
    $this->db->where('ProductCode', $q); 
    $query = $this->db->get('ProductList'); 
    if($query->num_rows > 0){ 
     foreach ($query->result_array() as $row){ 
      $row_set[] = htmlentities(stripslashes($row['m3'])); //build an array 
     } 
     return $row_set; 
    } 
    } 

這實際上是

select 'm3' from 'ProductList' where ProductCode='$1' 

我需要做的就是下面的查詢轉換成一個主動的記錄類型查詢並返回給什麼控制器按照上述活動記錄語法:

select length from 
(SELECT 
     [Length] 
     ,CONCAT(([width]*1000),([thickness]*1000),REPLACE([ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options 
    FROM [dbo].[dbo].[ProductList]) as p 
    where options='25100cr' order by length 

我圖片的東西像下面,但這不起作用。

$this->db->select(length); 
$this->db->from(SELECT [Length],CONCAT(([width]*1000),([thickness]*1000),REPLACE[ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options 
     FROM [dbo].[dbo].[ProductList]); 
$this->db->where(options, $q); 
$this->db->order(length, desc); 

幫助一如既往的讚賞。再次感謝。

+0

爲什麼不直接執行sql查詢呢? '$ this-> db-> query($ sql)' – Brewal

+0

@Brewal,不對注入或任何其他安全漏洞開放? – Smudger

回答

2

你可以使用codeigniter的子查詢方式來做到這一點,你將不得不破解codeigniter。這樣 進入系統/數據庫/ DB_active_rec.php從這些功能

public function _compile_select($select_override = FALSE) 
public function _reset_select() 

在現已子查詢書寫刪除公共或受保護的關鍵字,現在這裏是有活動記錄

$select = array(
       'Length' 
       'CONCAT(([width]*1000)', 
       'thickness * 1000', 
       'REPLACE(ProductCode, concat((width*1000),(thickness*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options' 
); 
$this->db->select($select); 
$this->db->from('ProductList'); 

$Subquery = $this->db->_compile_select(); 

$this->db->_reset_select(); 

$this->db->select('length'); 
$this->db->from("($Subquery)"); 
$this->db->where('options','25100cr'); 
$this->db->order_by('length'); 

而且查詢事情完成了。乾杯!!! 注意:使用子查詢,您必須使用

$this->db->from('myTable') 

代替

$this->db->get('myTable') 

它運行查詢。

Source

+0

嗨raheel,如何設置這整個查詢= $ q,所以我可以做'$ query = $ this-> db-> query($ sql); ($ query-> num_rows> 0)foreach($ query-> result_array()as $ row){ $ row_set [] = htmlentities(stripslashes($ row ['length'])); //建立一個數組 } return $ row_set; } }' – Smudger

+2

而不是'$ query = $ this-> db-> query($ sql)'use'$ query = $ this-> db-> get()'而不是你的if條件等等 –

+1

對於它的價值,查詢生成器不適用於像這樣的黑客行爲。如果你需要子查詢和什麼,你應該手動編寫查詢。您可以使用[查詢綁定](http://ellislab.com/codeigniter/user-guide/database/queries.html)確保您的數據已被轉義(建議在手動前進行適當的驗證)。 –