2011-05-15 27 views
2

我渴望得到給定的所有子類別在具有活動記錄codeigniter的where_in中使用。獲取結果形成一個查詢插入其他使用活動記錄

問題是第二個查詢與主要的查詢完全混淆。

主查詢

$this->db->select('artworks.*, users.id as owner, users.name as user_name'); 
$this->db->from('artworks'); 
$this->db->join('users', 'users.id = artworks.user_id'); 

$category = $this->get_child_categories($this->get_categories(), $matches[1]); 
$this->db->where_in('artworks.category', $this->category['child']); 

$this->db->group_by('artworks.id'); 
$query = $this->db->get(); 
return $query->result_array(); 

第二次查詢 「get_categories()」

$this->db->select('*'); 
$this->db->order_by('parent', 'asc'); 
$this->db->order_by('name', 'asc'); 
$query = $this->db->get('categories'); 
return $query->result_array(); 

get_child_categories

function get_child_categories($categories, $parent){ 
    foreach($categories as $category){ 
     if($category['parent'] == $parent){ 
      array_push($this->category['childs'], $category['id']); 
      $this->get_child_categories($categories, $category['id']); 
     } 
    } 
} 

,但我發現這個錯誤,其中清楚地顯示了第二個查詢在主要的內部提問。

Error Number: 1064 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM (`artworks`, `categories`) JOIN `users` ON `users`.`id` = `artworks`.`use' at line 1 

SELECT `artworks`.*, `users`.`id` as user_id, `users`.`name` as user_name, * FROM (`artworks`, `categories`) JOIN `users` ON `users`.`id` = `artworks`.`user_id` WHERE `artworks`.`rating` IN ('g', 'm', 'a') ORDER BY `artworks`.`id` desc, `parent` asc, `name` asc 

Filename: D:\Server\htdocs\gallery\system\database\DB_driver.php 

Line Number: 330 

回答

3

我個人認爲這是CodeIgniter的Active Record方法中的一個錯誤,如果它應該遵循Active Record模式的話。它應該完全執行的兩者之一:在一個單一的數據上下文包含在一個原子指令

由於這些都不是發生指定

  • 查詢

    • 查詢,在你的那一刻不情願地將兩個查詢與CodeIgniter不支持的結構混合在一起,從而創建無效查詢。

      對於一個簡單的解決方案,我會建議您反轉指令的順序,以便查詢分開執行。

      $category = $this->get_child_categories($this->get_categories(), $matches[1]); 
      # the first query gets executed here, your data context is cleaned up 
      
      $this->db->select('artworks.*, users.id as owner, users.name as user_name'); 
      $this->db->from('artworks'); 
      $this->db->join('users', 'users.id = artworks.user_id'); 
      $this->db->where_in('artworks.category', $this->category['child']); 
      $this->db->group_by('artworks.id'); 
      $query = $this->db->get(); 
      # your second query gets executed here 
      return $query->result_array(); 
      
  • 相關問題