Codeigniter - 在另一个查询中使用查询结果

时间:2013-05-03 09:17:57

标签: php mysql codeigniter object

在我的控制器中,我有一个查询结果列表(最多10行左右)。我试图使用查询的结果在另一个中使用。例如,第一个查询会提取“agency_ID”(我希望在下一个查询中使用的数据)

控制器:

$data['list_report'] = $this->reports_model->filteredReport();
$data['area_data'] = $this->reports_model->getAreaDataReport($data['list_report']);

MODEL:

function getAreaDataReport($data)
{       
    $query = $this->db->query('SELECT COUNT(asa.sector_ID) AS area_count, asa.*, ags.sector
    FROM agencies_sector_association asa, agencies_sector ags WHERE agency_ID IN ('. $data->agency_ID .')
    AND asa.agency_ID = ags.ID
    GROUP BY agency_ID');
    return $query->result();
}

我收到此错误:

Message: trying to get property of non-object codeigniter model

当我print_r第一个查询结果时,我得到以下内容。

Array ( [0] => stdClass Object ( [case_ID] => 1 [reference_ID] => IFSOU001 [ID] => 1 [agency_ID] => 1 [agency_name] => Agency1 [task_ID] => 3 [task] => Domestic violence [outcome_ID] => 3 [outcome] => Protection plan no longer in place [creation_date] => 2012-12-05 ) [1] => stdClass Object ( [case_ID] => 3 [reference_ID] => NEW REFERENCE ID [ID] => 2 [agency_ID] => 1 [agency_name] => Agency1 [task_ID] => 1 [task] => Transport [outcome_ID] => 8 [outcome] => Bespoke needs based assessment received [creation_date] => 2013-05-01 ) [2] => stdClass Object ( [case_ID] => 6 [reference_ID] => REFERENCE ID [ID] => 6 [agency_ID] => 1 [agency_name] => Agency1 [task_ID] => 2 [task] => Counselling [outcome_ID] => 2 [outcome] => Improved school attendance [creation_date] => 2013-05-01 ) )

我的问题是如何将我的下一个语句中第一个语句的agency_ID用作数组,这样它就不会返回一行。从这个结果我得到了3'agent_ID'的结果,但在未来的搜索中可能更多。

非常感谢所有能提供帮助的人!

2 个答案:

答案 0 :(得分:1)

$data是一个只包含一个对象的对象数组。

$data->agency_ID替换为$data[0]->agency_ID

这将为您提供agency_ID数组中位置[0]处存储的对象的$data成员变量。

假设结果数组中有多个对象,您需要获取ID并将它们存储在字符串中,然后在查询中使用此字符串

$id_str = '';
foreach($data as $agency) {
    $id_str .= $agency->agency_ID . ', ';
}
$id_str = rtrim($id_str, ', '); //remove the trailing comma and space

现在使用$data->agency_ID

替换查询中的$id_str

答案 1 :(得分:0)

您必须重新格式化结果数组,使其适合IN语句。采用23, 17, 20之类的格式。 $this->reports_model->filteredReport();应该以{{1​​}}返回。

result_array()

然后只需在查询中使用该字符串:

$data['list_report'] = $this->reports_model->filteredReport();

$data_list = array();

foreach($data['list_report'] as $lp) {
    $data_list[] = $lp->agency_ID;
}

$data['area_data'] = $this->reports_model->getAreaDataReport(implode(',',$data_list));