如何在Codeigniter中使用ORM从两个连接在一起的表中进行选择?

时间:2012-10-08 05:40:27

标签: codeigniter orm

我希望在Codeigniter中的ORM中显示与下面的SQL代码(它的工作原理)相同的东西:

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子句根本不起作用

我提供下面的表格结构

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;

2 个答案:

答案 0 :(得分:1)

您应该知道活动记录不是ORM。如果你想通过活动记录得到这个,你可以这样做。有关详细信息,请阅读Codeigniter的用户指南

$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); 

答案 1 :(得分:-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();