-1

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

それは機能しません、selectの代わりに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;
4

2 に答える 2

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); 
于 2012-10-08T06:57:29.940 に答える
-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();
于 2012-10-08T06:58:26.187 に答える