php - Codeigniter 事件记录类错误与 MySQL 原始查询

标签 php mysql codeigniter activerecord

在我的模型中,我用MySQL原始查询编写了这个函数

function get_question_result($lr_id)
{
    $raw_query = 'SELECT question_record.qr_id, LEFT(question.question, 50) as question,
                    question.correct_answer
                    FROM question_record
                    INNER JOIN question ON question.q_id = question_record.q_id
                    WHERE question_record.lr_id = '.$lr_id.' ';
    $query = $this->db->query($raw_query);
    $questionresult = $query->result_array();
    return $questionresult;
}

工作 很好。它给了我想要的数组。我继续我的项目。

突然间我很好奇想在 CI Active Record Class 中尝试一下。

function get_question_result($lr_id)
{
    $this->db->select('question_record.qr_id, LEFT(question.question, 50) as question, question.correct_answer');
    $this->db->from('question_record');
    $this->db->join('question', 'question.q_id = question_record.q_id', 'inner');
    $this->db->where('question_record.lr_id', $lr_id);
    $result = $this->db->get()->result_array();
    return $result;
}

它没有用。它给了我这个错误

PHP Fatal error:  Call to a member function result_array() on a non-object 

只是出于好奇,我哪里做错了? 是我写错了还是 Active Record 的结果数据结构不一样?

'因为当我在 Active Record 中再次尝试时没有选择这个字段

LEFT(question.question, 50) as question

有效但没有提供我想要的字段。你们知道为什么吗?

最佳答案

在您的 $this->db->select() 调用中,您需要将 FALSE 作为第二个参数传递,以便事件记录不会尝试为您添加反引号 `选择语句中的列

function get_question_result($lr_id)
{
    $this->db->select('question_record.qr_id, LEFT(question.question, 50) as question, question.correct_answer',FALSE);
    $this->db->from('question_record');
    $this->db->join('question', 'question.q_id = question_record.q_id', 'inner');
    $this->db->where('question_record.lr_id', $lr_id);
    $result = $this->db->get()->result_array();
    return $result;
} 

根据文档

$this->db->select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks. This is useful if you need a compound select statement.

$this->db->select();

关于php - Codeigniter 事件记录类错误与 MySQL 原始查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34569547/

相关文章:

php - 将 SQL 数据放入 HTML 表

php - 在 1 个查询中将数据插入到 3 个表中

mysql - mysql 中按值等于 0 或不存在的行的行进行分组?

php - 我想从具有参数的 codeigniter URL 中删除索引

javascript - Codeigniter session flashdata 和 ajax

php - 跨多个服务器的 Laravel Task Scheduler 没有重叠

javascript - 表单提交后运行脚本和php

mysql - timediff 大于 2 分钟

php - codeigniter 中的 group by 和 count 计数不正确

php - wordpress 导出 csv 在管理菜单页面中不起作用