php - LEFT JOIN 关联返回未知列

标签 php mysql codeigniter phpactiverecord

我正在使用 PHPActiveRecord 和 CodeIgniter。我正在尝试创建一个博客 CMS,一个博客有很多类别,它引用另一个名为 blogrefs 的表。所以基本上

博客 => blogrefs => blogcats

blogrefs 通过 blogrefs.blog_id 引用博客

blogrefs 通过 blogrefs.blogcat_id 引用 blogcats

    function get_blogs($params = array()){

    $CI =& get_instance();

    $joins  = 'LEFT JOIN blogrefs ON blogs.id = blogrefs.blog_id';
    $joins  .= 'LEFT JOIN blogcats ON blogrefs.blogcat_id = blogcats.id';
    $category = (isset($params['category']))?$params['category']:'';
    $keyword = (isset($params['keyword']))?$params['keyword']:'';
    $status = (!isset($params['status']) || $params['status'] == '')?'':$params['status'];
    $order_by = (isset($params['order_by']))?$params['order_by']:'created_on';
    $direction = (isset($params['direction']))?$params['direction']:'DESC';
    $limit = (isset($params['limit']))?$params['limit']:'';
    $offset = (isset($params['offset']))?$params['offset']:'';
    $st = '';
    if($status == ''){
        $st = '!';
    }

        if(!empty($category))
        {
            $conditions = array(
                "((blogcats.id = ?) OR (blogcats.parent_id = ?))
                 AND blogs.status $st= ?
                 AND (blogs.title LIKE '%$keyword%' OR blogs.content LIKE '%$keyword%')",$category,$category,$status
            );

        }else{
            $conditions = array(
                "blogs.status $st= ?
                 AND (blogs.title LIKE '%$keyword%' OR blogs.content LIKE '%$keyword%')",$status
            );
        }

    $result = Blog::find('all',array(
        'include'       => array('blogcat','blogref','user'),
        'joins'         => $joins,
        'conditions'    => $conditions,
        'limit'         => $limit,
        'offset'        => $offset,
        'order'         => "$order_by $direction",
        'group'         => 'blogs.id'
    ));

    $count =  Blog::find('all',array(
        'conditions'    => $conditions
    ));

    $object = new stdClass;
    $object->posts = $result;
    $object->total = count($count);
    return $object;

}

不仅我使用一切正常

((blogcats.id = ?) 或 (blogcats.parent_id = ?))

获取特定类别的博客。任何答案将不胜感激。

最佳答案

我觉得这不是很清楚。为什么不使用模型和 CI 的 Active Record 类? ( http://ellislab.com/codeigniter/user-guide/database/active_record.html ), 喜欢

    $this->db->where('blogrefs.blogcat_id', $catid);
    $this->db->join('blogrefs', 'blogs.id = blogrefs.blog_id');
    ...

关于php - LEFT JOIN 关联返回未知列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15690285/

相关文章:

mysql - JPA + MySQL : After Timeout --> use a local Connection

MySQL 具有 union/join 和同一列上的两个别名

php - 这个正则表达式有什么作用

php - 奇怪的MySQLi错误

php - 如何在一个服务器中创建表,就像从另一个表创建表一样

c# - MVC3 中的 "Hooks"

activerecord - Codeigniter:从多个表中选择

php - 使用 PHP 向 IOS 设备发送通知

javascript - 生成随机数和字符 - MYSQL

mysql - 如何将值添加到 doctrine 中的数组模型?