2012-07-09 44 views
0

我刚开始使用Codeigniter,这让我感到非常紧张。我有一个查询来确定用户是否购买了任何程序。然后,我必须使用该程序的类型类别来运行并确定他或她在另一个表中记录了多少次查询。对于混淆抱歉,但代码希望是有道理的。Codeigniter的多个/子查询

我有问题将两个数组从我的模型返回到我的控制器到显然视图上。

function specificPrograms() { 
$specific_sql = $this->db->query("SELECT program,created FROM `assessment` WHERE uid = $this->uid"); 
if($specific_sql->num_rows() > 0) { 
foreach ($specific_sql->result() as $specific) {   
$data[] = $specific; 
$this->type = $specific->program; 
} 
return $data; 
} 

$sub_sql = $this->db->query("SELECT id FROM othertable WHERE user_id_fk = $this->uid and type = '$this->type'"); 
if($sub_sql->num_rows() > 0) { 
foreach ($sub_sql->result() as $otherp) {  
$data[] = $otherp; 
} 
return $data; 
} 

} 

然后在我的控制器我有,

$data['specific'] = $this->user_model->specificPrograms(); 
$data['otherp'] = $this->user_model->specificPrograms(); 

感谢您的帮助。

+0

您能描述一下您对代码的期望吗?在运行之后,你希望'$ data ['specific']'和'$ data ['otherp']'被设置为什么?他们现在做了什么? – 2012-07-09 03:18:13

+0

当然,基本上。假设用户购买了3个独立的程序,并且对于每个程序,他或她已经使用了它一定次数,这个数字将被记录为来自其他人的ID。例如,Bob购买了产品1,产品2和产品3.我需要知道Bob购买的“程序”以及与其产品或类型相对应的其他ID是否已记录在其他产品或类型中。这有任何意义吗? – user1011713 2012-07-09 03:21:31

+0

对不起,让我们试试更好的例子:鲍勃购买了3种不同的锻炼:棒球,篮球和足球锻炼。对于每个人都已经完成了一定数量的锻炼,这些锻炼将被记录并使用第二个sql查询返回的num-rows。我需要这项运动(篮球,足球,棒球......)以及鲍勃为每项运动所做的锻炼次数(计数ID)。 – user1011713 2012-07-09 03:23:26

回答

1

根据您上面的意见,我建议一个查询返回您需要的结果。其结果集如下所示:

+----------+------------+------+ 
| program | created | uses | 
+----------+------------+------+ 
| football | 2001-01-01 | 12 | 
+----------+------------+------+ 
| baseball | 2007-01-01 | 21 | 
+----------+------------+------+ 


SELECT 
    assessment.program, 
    assessment.created, 
    count(othertable.user_id) as uses 
FROM assessment 
JOIN othertable 
    ON othertable.user_id_fk = assessment.uid 
    AND othertable.type = assessment.program 
WHERE assessment.uid = $this->uid 
GROUP BY assessment.program 

... model ... 

function specificPrograms() { 
    $results = $this->db->query($sql_from_above); 
    if($specific_sql->num_rows() > 0) { 
    foreach ($specific_sql->result() as $program_data) {   
    $data[] = $program_data; 
    } 
    return $data; 
} 

... meanwhile in controller ... 


$programs_used = $this->user_model->specificPrograms(); 
foreach($programs_used as $program_use_data) { 
    // On first iteration, this is true: 
    // $program_use_data['program'] == "football" 
    // $program_use_date['uses'] == 12 
} 
+0

当前尝试了这一点。 – user1011713 2012-07-09 03:45:36

+0

不幸的是我无法让它工作。我收到错误,'为foreach()提供的无效参数'。有什么建议么? – user1011713 2012-07-09 06:16:43

+0

对不起,我忘了从模型函数中返回$ data: -/fixed。 – 2012-07-09 06:25:20