php – 使用Active Record在CodeIgniter中加入SQL

我试图绕过这个,但我似乎是围成一圈.我正在尝试逐个列出用户主题,下面是属于该特定主题的引号.如果这是有道理的.

我有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失败的位置进行有效评估.

要使用分析器,请将其粘贴到控制器中:

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

它将导致所有数据库调用,所有POST变量等的良好输出;
参考这里:http://codeigniter.com/user_guide/libraries/output.html

UPDATE

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

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排序,如果它是同一个人,则在第二个循环上进行测试,否则输出新用户名).

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...