我试图在phpactiverecord查询中转换我的sql查询。但它不起作用。我收到此错误消息:
Fatal error: Uncaught exception 'ActiveRecord\DatabaseException' with message '42S02, 1109,
Unknown table 'c' in field list' in ..\activerecord\lib\Connection.php:277
Stack trace: #0 ..\inc\activerecord\lib\Table.php(208): ActiveRecord\Connection->query('SELECT distinct...', NULL)
#1 ..\inc\activerecord\lib\Model.php(1481): ActiveRecord\Table->find_by_sql('SELECT distinct...', NULL, true)
#2 ..\zexport.php(100): ActiveRecord\Model::find_by_sql('SELECT distinct...')
#3 {main} thrown in ..\inc\activerecord\lib\Connection.php on line 277
这是我的尝试:
$totalvalues = RefTable::find_by_sql("SELECT distinct c.code, p.gestion");
for ($i = 1; $i <= count($steps); $i++) {
$totalvalues.=RefTable::find_by_sql(",(SELECT IFNULL(ROUND(SUM(c".$i.".`delta`),1),'')
FROM charge c".$i.", totalgestion p".$i."
WHERE c".$i.".code = p.code
AND c".$i.".steps = ".$i."
AND c".$i.".actif = 1) as delta".$i.",'' as comments".$i.",
(SELECT IFNULL(ROUND(SUM(c".$i.".`values`),1),'')
FROM charges c".$i.", totalgestion p".$i."
WHERE c".$i.".code = p".$i.".code
AND c".$i.".year = ".$year."
AND c".$i.".steps = ".$i." ");
}
$totalvalues .=RefTable::find_by_sql("FROM charges c, totalgestion p
WHERE c.code = p.code
AND c.annee = ".$year."
AND c.type = 1") ;
foreach ($totalvalues as $totalvalue) {
$Code = $totalvalue->code;
$Delta = $totalvalue->delta;
echo $Code . ' - ' .$Delta;
}
这个查询工作正常,但我是php activerecord的新手,所以我希望有人能告诉我这里我犯的错误。
提前致谢
答案 0 :(得分:0)
RefTable::find_by_sql
不是查询构建器。每次调用它时,它都在执行一条SQL语句。知道这一点,很容易看出第一次呼叫失败的原因。试试这个:
$sql = "SELECT distinct c.code, p.gestion";
for ($i = 1; $i <= count($steps); $i++) {
$sql .= "
,(SELECT IFNULL(ROUND(SUM(c".$i.".`delta`),1),'')
FROM charge c".$i.", totalgestion p".$i."
WHERE c".$i.".code = p.code
AND c".$i.".steps = ".$i."
AND c".$i.".actif = 1) as delta".$i.",'' as comments".$i.",
(SELECT IFNULL(ROUND(SUM(c".$i.".`values`),1),'')
FROM charges c".$i.", totalgestion p".$i."
WHERE c".$i.".code = p".$i.".code
AND c".$i.".year = ".$year."
AND c".$i.".steps = ".$i." "
;
}
$sql .= "
FROM charges c, totalgestion p
WHERE c.code = p.code
AND c.annee = ".$year."
AND c.type = 1
";
$totalvalues = RefTable::find_by_sql($sql);