2012-10-08 21 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(); 
相关问题