2011-05-15 32 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(); 
      
  • 相关问题