【发布时间】:2010-10-21 22:14:03
【问题描述】:
我有一个博客风格的应用程序,它允许用户用主题标记每个帖子。我将这些数据保存在三个单独的表中:posts(用于实际的博客文章)、topics(用于各种标签)和 posts_topics(存储两者之间关系的表)。
为了使 MVC 结构(我正在使用 Codeigniter)尽可能干净,我想运行一个 MySQL 查询来获取所有帖子数据和相关主题数据,并将其返回到一个数组或对象中。到目前为止,我没有任何运气。
表结构是这样的:
Posts
+--------+---------------+------------+-----------+--------------+---------------+
|post_id | post_user_id | post_title | post_body | post_created | post_modified |
+--------+---------------+------------+-----------+--------------+---------------+
| 1 | 1 | Post 1 | Body 1 | 00-00-00 | 00-00-00 |
| 2 | 1 | Post 1 | Body 1 | 00-00-00 | 00-00-00 |
+--------+---------------+------------+-----------+--------------+---------------+
// this table governs relationships between posts and topics
Posts_topics
+--------------+---------------------+-------------------------+-----------------+
|post_topic_id | post_topic_post_id | post_topic_topic_id | post_topic_created |
+--------------+---------------------+-------------------------+-----------------+
| 1 | 1 | 1 | 00-00-00 |
| 2 | 1 | 2 | 00-00-00 |
| 3 | 2 | 2 | 00-00-00 |
| 4 | 2 | 3 | 00-00-00 |
+--------------+---------------------+-------------------------+-----------------+
Topics
+---------+-------------+-----------+----------------+
|topic_id | topic_name | topic_num | topic_modified |
+---------+-------------+-----------+----------------+
| 1 | Politics | 1 | 00-00-00 |
| 2 | Religion | 2 | 00-00-00 |
| 3 | Sports | 1 | 00-00-00 |
+---------+-------------+-----------+----------------+
我已经成功地尝试了这个简单的查询:
select * from posts as p inner join posts_topics as pt on pt.post_topic_post_id = post_id join topics as t on t.topic_id = pt.post_topic_topic id
我也尝试过使用 GROUP_CONCAT,但这给我带来了两个问题:1) 我需要主题中的所有字段,而不仅仅是名称,以及 2) 我的 MySQL 出现故障,因此所有 GROUP_CONCAT 数据都返回为一个 BLOB(请参阅 here)。
我也愿意听取我运行两个查询并尝试为每个结果构建一个数组的任何建议;我用下面的代码尝试过,但失败了(这段代码还包括加入用户表,保留它也很好):
$this->db->select('u.username,u.id,s.*');
$this->db->from('posts as p');
$this->db->join('users as u', 'u.id = s.post_user_id');
$this->db->order_by('post_modified', 'desc');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$posts = $query->result_array();
foreach($posts as $p)
{
$this->db->from('posts_topics as p');
$this->db->join('topics as t','t.topic_id = p.post_topic_topic_id');
$this->db->where('p.post_topic_post_id',$p['post_id']);
$this->db->order_by('t.topic_name','asc');
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach($query->result_array() as $t)
{
$p['topics'][$t['topic_name']] = $t;
}
}
}
return $posts;
}
非常感谢任何帮助。
【问题讨论】:
标签: php activerecord codeigniter mysql