2012-10-08 20 views
-1

我想實現象下面這樣笨的ORM所示的SQL代碼(它的工作原理)同樣的事情:如何在Codeigniter中使用ORM從兩個表連接起來進行選擇?

SELECT question.`id`,`title`,`question`,`answer` FROM answer LEFT JOIN question ON answer.question_id = question.id WHERE question.`id` = 1 

我做了如下代碼:

$this->db->select('question.id, question.title, question.question, answer.answer')->from('answer')->join('question', 'answer.question_id = question_id')->where('question.id',1); 
$query = $this->db->get(); 

這是行不通的,而不是中選擇question.id = 1,它讓所有的答案,這似乎是在where子句中完全不

我提供以下

的表結構0
CREATE TABLE `question` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
    `title` varchar(128) NOT NULL DEFAULT '', 
    `question` text NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; 


CREATE TABLE `answer` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
    `question_id` int(11) unsigned NOT NULL, 
    `answer` text NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `question_id` (`question_id`), 
    CONSTRAINT `answer_ibfk_1` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`) ON DELETE CASCADE ON UPDATE CASCADE 
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1; 
+0

是否使用的是ORM? –

+0

@raheelshan我正在使用Codeigniter構建在活動記錄 – mko

+0

@raheelshan我自己發現了這個問題,我使用數組錯誤 – mko

回答

1

你應該知道活動記錄不是ORM。如果你想獲得積極的記錄這裏是你如何做到這一點。詳細閱讀笨

$data = array(
       answer.question_id, 
       answer.title, 
       question.question, 
       answer.answer , 
       question.id, 
      ); 
$this->db->select($data); 
$this->db->from('answer'); 
$this->db->join('question','answer.question_id = question.id ','left'); 
$this->db->where('question.id',1); 
+0

+1來傳遞給'select',優雅! – mko

-1

的用戶指南,我發現在我的問題是:

$this->db->select('question.id, question.title, question.question, answer.answer')->from('answer')->join('question', 'answer.question_id = question_id')->where('question.id',1); 
$query = $this->db->get(); 

應該是:

$this->db->select('question.id, question.title, question.question, answer.answer')->from('answer')->join('question', 'answer.question_id = **question.id**')->where('question.id',1); 
$query = $this->db->get(); 
相關問題