2013-03-28 114 views
1

我正在使用PHPActiveRecord和CodeIgniter。我正在嘗試創建一個博客CMS,並且博客有許多類別,並且引用了另一個名爲blogrefs的表。所以基本上LEFT JOIN Association返回未知列

博客=> blogrefs => blogcats

blogrefs通過blogrefs.blog_id

blogrefs有博客指通過blogrefs.blogcat_id

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指作品不僅如果我使用

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

從特定類別獲取博客。任何答案將非常感激。

+0

如果您使用phpactiverrecord,沒有更快的方法來獲取所有這些相關的對象嗎?喜歡使用關聯? – Nanne

回答

0

您的錯誤是在您定義連接的第一部分的末尾缺失的空間。

$joins = 'LEFT JOIN blogrefs ON blogs.id = blogrefs.blog_id'; 
$joins .= 'LEFT JOIN blogcats ON blogrefs.blogcat_id = blogcats.id'; 

計算結果爲:

LEFT JOIN blogrefs ON blogs.id = blogrefs.blog_idLEFT JOIN blogcats ON blogrefs.blogcat_id = blogcats.id 

你會發現,第一個連接是通過尋找一個名爲「blog_idLEFT」列和第二搞砸了現在加入將是一個內部聯接,不外部左連接。

我建議或者使用davedriesmans的建議,或者找出一些方法輸出最終生成的mySQL查詢。 (或兩者)