【问题标题】:Getting results form a query to insert in other using active records使用活动记录从查询中获取结果以插入其他
【发布时间】:2011-05-15 16:13:58
【问题描述】:

我需要从给定中获取所有子类别,以便在带有 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

【问题讨论】:

    标签: codeigniter activerecord


    【解决方案1】:

    我个人认为这是 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 2016-05-27
      相关资源
      最近更新 更多