从查询中获取结果以使用活动记录插入其他查询

时间:2011-05-15 16:13:59

标签: codeigniter activerecord

我现在需要从给定的所有子类别中使用带有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

1 个答案:

答案 0 :(得分: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();