php - SQL 在 CodeIgniter 中加入 Active Record

标签 php codeigniter activerecord

我正在努力解决这个问题,但我似乎在兜圈子。我试图一个一个地列出用户主题,下面是属于该特定主题的引号。如果这是有道理的话。

我有 3 个表,像这样:

[USERS] user_id username

[TOPICS] topic_id user_id topic_name

[QUOTES] quote_id topic_id quote_name

在我看来,我希望能够做这样的事情:

Username: Thomas

Topic 1: Whatever

Quotes: One quote, another quote, and a third quote, all belonging to Topic 1.

Topic 2: Another topic from Thomas

Quotes: Yes indeed, Okay thanks, I love Stack Overflow, These quotes belong to Topic 2.

但我无法让它工作,我一直在尝试一切,包括奇怪的东西,比如:

public function get_quotes()
{

    $this->db->select('*');
    $this->db->from('topics');
    $this->db->join('quotes', 'topic_id = quote_id');

    $query = $this->db->get();

    if($query->num_rows() > 0)
    {
        foreach ($query->result() as $row) {
            $data[] = $row;
        }
    }
    return $data;
}

这很奇怪吗,我应该改为尝试使用“where”吗?像这样的东西:

$this->db->where('user', $user_id);
$this->db->where('topic', $topic_id);
$this->db->where('quote', $quote_id);

我非常感谢我能得到的任何帮助,或者只是指点正确的方向!

最佳答案

我会立即问“什么不工作?”,其次我建议您运行探查器以显示正在生成的EXACT SQL,所以您可以对 ACTIVE QUERY 使您失败的地方做出有效评估。

要使用分析器,请将其粘贴到您的 Controller 中:

$this->output->enable_profiler(TRUE);

这将导致所有数据库调用、所有 POST 变量等的良好输出;
此处引用:http://codeigniter.com/user_guide/libraries/output.html

更新

因此,要完全执行您想要的操作,您需要一个返回以下列的查询:

user_id, username, topic_id, topic_name, quote_id, quote_name

这是您想要的事件查询(如果足够清楚,您也可以使用方法链接):

$this->db->select('u.user_id, u.username, t.topic_id, t.topic_name, q.quote_id, q.quote_name');
$this->db->from('users u');
$this->db->join('topics t', 't.user_id = u.user_id'); // this joins the user table to topics
$this->db->join('quotes q', 'q.topic_id = t.topic_id'); // this joins the quote table to the topics table
$query = $this->db->get();

您的结果集将类似于:

user_id     | username  | topic_id  | topic_name    | quote_id  | quote_name
1           |Thomas     |1          |Whatever       |1          |One quote, anot...
2           |Ryan       |4          |Another...     |6          |To be or not to...

一旦你有了那个结果集,简单地遍历数据输出它,并检查你是否有来自同一个人的多个引号(比如按 user_id 排序,如果是同一个人,则在第二个循环上进行测试,否则输出新用户名)。

关于php - SQL 在 CodeIgniter 中加入 Active Record,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9333392/

相关文章:

php - 在 SQL Select 中返回零

php - 整个站点在 IE 6、7、8 中根本无法加载,在 9 中出现 CSS 问题

codeigniter - 如何从 codeigniter 中的另一个 Controller 调用 Controller ?

php - 从SQL中的文本字段中提取单词

javascript - 我如何仅使用 javascript 获取事件类的索引

php - 在 Docker 中启用 Apache SSL 以进行本地开发

php - 使用我的 PHP 服务将 AngularJS 连接到 mysql?

php - 在CodeIgniter中查看update_batch()是否成功

codeigniter - 使用CodeIgniter购物车是否安全?

ruby-on-rails - ActiveRecord::DangerousAttributeError - 属性?由 ActiveRecord 定义