【问题标题】:PHP: Active record table joinsPHP:活动记录表连接
【发布时间】:2011-01-14 20:03:57
【问题描述】:

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

数据库结构如下:

帖子

身份证

tags_ref

row_id

表格

tag_id

标签

身份证

安全标签

标签

如果 $safe_tag 不为空,则我的查询基本上是在 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 为空时,查询可以完美运行,但如果不是,我会得到错误的结果。

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' 

有人可以看看吗?我想我需要重新审视它。

【问题讨论】:

  • «很遗憾,我在活动记录中编写的查询无法正常运行» — 返回任何错误或意外数据集?在执行之前,你能用你的 $this->db 看到(调试)SQL 查询作为字符串吗?
  • 我发现 CI Active Record 类的限制非常严格,仅用于更新和插入。除此之外,只需使用 $db->query("SELECT * FROM table WHERE id=?",array($id))。您不必像为代码中的附加连接子句所做的那样妥协,也不会在服务器上造成额外的负载来解析您的活动记录查询。抱歉,我知道这并不能真正回答您的问题,只是想分享我的想法。
  • 顺便说一句,您可以通过打开 profiling (codeigniter.com/user_guide/general/profiling.html) 来查看执行的查询。
  • 直接在数据库上运行 SQL 查询的结果是什么,它们与通过 Active Record 运行返回的结果有何不同?
  • 活动记录查询不等同于您在上面发布的标准 sql 查询 - 它有一个额外的 where 'tags_ref.table' 子句?

标签: php codeigniter activerecord


【解决方案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 
    }

【讨论】:

    猜你喜欢
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 2013-08-02
    相关资源
    最近更新 更多