PHP:活动记录表连接

时间:2011-01-14 20:03:58

标签: php codeigniter activerecord

我有一个使用codeigniter CXTags标记库的应用程序。

数据库结构如下:

帖子

ID

tags_ref

ROW_ID

TAG_ID

代码

ID

safe_tag

标签

我的查询基本上是在$ safe_tag不为null的情况下然后在post.id = tags_ref.row_id上加入tags_ref,在tags_ref.tag_id = tags.id上加入标签,其中tags_ref.table ='posts'和tags.safe_tag ='食品

SELECT * FROM posts 
JOIN tags_ref ON posts.id = tags_ref.row_id
JOIN tags ON tags_ref.tag_id = tags.id
WHERE tags.safe_tag = $safe_id

不幸的是,我在活动记录中写的查询无法正常运行。当£safe_tag为null但查询结果不正确时,查询效果非常好。

function get_posts($id = NULL, $safe_tag = NULL) {

    if($safe_tag != NULL){
        echo $safe_tag;//debugging
        $table = 'posts';
        $this->db->join('tags_ref', 'posts.id = tags_ref.row_id');
        $this->db->join('tags', 'tags_ref.tag_id = tags.id');
        $this->db->where('tags_ref.table', $table);
        $this->db->where('tags.safe_tag',$safe_tag);
    }

    //if an id was supplied
    if ( $id != NULL ) {
        $this->db->where('posts.city_id',$id);
    }

    // execute query
    $query = $this->db->get('posts');
    ...

以下是带有分析的查询:

SELECT *
FROM (`posts`)
INNER JOIN `tags_ref` ON `posts`.`id` = `tags_ref`.`row_id`
INNER JOIN `tags` ON `tags_ref`.`tag_id` = `tags`.`id`
WHERE `tags_ref`.`table` = 'posts'
AND `tags`.`safe_tag` = 'food'
AND `posts`.`city_id` = '2' 

有人可以看看吗?我想我需要一双新鲜的眼睛。

1 个答案:

答案 0 :(得分:1)

您忘记在第一个if{}

中实际运行查询
if($safe_tag != NULL){
        echo $safe_tag;//debugging
        $table = 'posts';
        $this->db->join('tags_ref', 'posts.id = tags_ref.row_id');
        $this->db->join('tags', 'tags_ref.tag_id = tags.id');
        $this->db->where('tags_ref.table', $table);
        $this->db->where('tags.safe_tag',$safe_tag);
        $this->db->get(); // here 
    }
相关问题