我需要从给定中获取所有子类别,以便在具有 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();
获取子类别
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
最佳答案
我个人认为,如果 CodeIgniter 应该遵循 Active Record 模式,那么这是 CodeIgniter 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();
关于codeigniter - 从查询中获取结果以插入到其他使用事件记录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6009608/