gpt4 book ai didi

php - SQL 在 CodeIgniter 中加入 Active Record

转载 作者:可可西里 更新时间:2023-11-01 13:13:44 26 4
gpt4 key购买 nike

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

我有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com