2012-02-24 220 views
1

我正在研究Codeigniter中的查詢,我試圖保持它看起來乾淨。我甚至還沒有添加大部分字段,我可以看到它變得笨拙,特別是select_sum的。Codeigniter查詢鏈接

有沒有寫他們還是有辦法把它們混合起來的更清潔的方式?

$this->db->select('Map'); 
$this->db->select_sum('Kills')->select_sum('Deaths')->select_sum('Win')->select_sum('Loss')->select_sum('Win + Loss', 'GP'); 
$this->db->from('games'); 
$this->db->where('Name', $player_name); 
$this->db->join('players', 'players.PlayerID = games.PlayerID'); 
$this->db->join('gameinfo', 'games.GameID = gameinfo.GameID'); 
$this->db->group_by('Map'); 
$this->db->order_by('Kills', "desc"); 
$this->db->limit(10); 

$query = $this->db->get(); 

return $query->result_array(); 
+0

看上去幹淨給我! – 2012-02-24 02:46:29

回答

3

原始SQL是我的建議。

$name = $this->db->escape($player_name); 

$sql = " 
    SELECT Map, SUM(Kills), SUM(Deaths), SUM(Win), SUM(Loss), SUM(Win + Loss) AS GP 
    FROM games 
    JOIN players ON (players.PlayerID = games.PlayerID) 
    JOIN gameinfo ON (games.GameID = gameinfo.GameID) 
    WHERE Name = $name 
    GROUP BY Map 
    ORDER BY Kills DESC 
    LIMIT 10 
"; 

$query = $this->db->query($sql); 

return $query->result_array(); 

在我看來,只要我們能做出漂亮的縮進,它比CI活動記錄的版本更具有可讀性。

+0

那麼dinamically創建的查詢呢?在這種情況下使用CI的AR很舒服。 – uzsolt 2012-02-24 10:37:35

+0

是的,當然。這完全取決於。我沒有反對使用CI的AR。我確實使用它!它有很多好處,當然。這只是一個**,有時是**,在純SQL中編寫和讀取查詢要比在頭上進行轉換或調用'$ this-> db-> last_query()'來發現什麼更容易AR構建的最終查詢看起來像。 – 2012-02-25 00:05:56

1

我使用類似這樣的:

$this->db->select("map_name") 
    ->from("maptables") 
    ->where("maptables.id",2); 

對於我來說,可讀:)

(我做了一個自己的庫,它確實喜歡AR相似 - 因爲AR有一些錯誤)

0

你也可以把它寫這種方式在我看來,這是更具可讀性

$this->db->select('Map, SUM(Kills), SUM(Deaths), SUM(Win), SUM(Loss), SUM(Win + Loss, GP)'); 
$this->db->from('games');<br /> 
$this->db->where('Name', $player_name);<br /> 
$this->db->join('players', 'players.PlayerID = games.PlayerID');<br /> 
$this->db->join('gameinfo', 'games.GameID = gameinfo.GameID');<br /> 
$this->db->group_by('Map');<br /> 
$this->db->order_by('Kills', "desc");<br /> 
$this->db->limit(10);<br /> 

$query = $this->db->get(); 

return $query->result_array();`