2010-06-06 49 views
4

我已經在Codeigniter中介紹了activerecord和手動查詢。當所有關於標準查詢並且開發時間非常短的時候,ActiveRecord都非常棒。Codeigniter:結合activeRecord和手動查詢?

但是,當需要爲查詢添加一些複雜性時,ActiveRecord會變得非常複雜。子查詢或複雜的聯接給了我很多頭痛。

由於當前「$ this-> db-> query」調用立即執行設置的查詢,因此它不能與正常的activeRecord調用結合使用。

那麼,我能做些什麼來結合這兩種方法呢?什麼我要完成

例子:

$this->db->select('title, content, date'); 
$this->db->from('mytable'); 
$this->db->manual('UNION'); // My own idea of db-call that appends UNION to the query 
$this->db->select('title, content, date'); 
$this->db->from('mytable2'); 
$query = $this->db->get(); 

謝謝!

+1

我們展示了一個複雜的查詢的聯合國例子,也許我們可以想想,我們如何能夠用做ActiveRecord的。 AFAIK你不能結合$ this-> db-> query()+ $ this-> db-> get(),如果這是你的意思。 – Bogdan 2010-06-06 18:40:42

+0

嗨,這實際上是我一直在想的事情,所以我恐怕現在我沒有一個具體的例子。正如你所說,我知道$ this-> db-> query()+ $ this-> db-> get()不能合併:) – Industrial 2010-06-06 18:43:21

+0

我與Bogdan,一個示例查詢會很好。 – DRL 2010-06-07 10:04:10

回答

4

也許這個鏈接將幫助:active record subqueries

更新---

共有約Union with Codeigniter Active Record另議。我同意那裏的答案。

但是對於一些子查詢,我們可以將活動記錄與手動查詢結合起來。例如:

// #1 SubQueries no.1 ------------------------------------------- 

$this->db->select('title, content, date'); 
$this->db->from('mytable'); 
$query = $this->db->get(); 
$subQuery1 = $this->db->_compile_select(); 

$this->db->_reset_select(); 

// #2 SubQueries no.2 ------------------------------------------- 

$this->db->select('title, content, date'); 
$this->db->from('mytable2'); 
$query = $this->db->get(); 
$subQuery2 = $this->db->_compile_select(); 

$this->db->_reset_select(); 

// #3 Union with Simple Manual Queries -------------------------- 

$this->db->query("select * from ($subQuery1 UNION $subQuery2) as unionTable"); 

// #3 (alternative) Union with another Active Record ------------ 

$this->db->from("($subQuery1 UNION $subQuery2)"); 
$this->db->get(); 

注:對不起,我沒有測試過這個劇本,希望它的作品,樂於助人..

+0

嗨Bakazero。感謝您的鏈接。非常感激。請檢查我的原始帖子。用我想要做的一個例子更新它。 – Industrial 2010-06-09 11:27:32

+0

嗨!喜歡你的更新很多。不像我想要的那樣乾淨。給予好評! :) – Industrial 2010-06-11 19:50:44

+0

這不起作用(或不再有效)。 _compile_select和_reset_select是受保護的方法。 – mpemburn 2013-07-29 16:05:55