我正在CI中设计一个应用程序,经过几次尝试后能够建立sql查询:
select inv2.id,inv1.uniqueid,inv2.pastamount_due, c.name FROM invoices as inv2 join (SELECT max(id) as maxid, uniqueid from invoices GROUP by uniqueid ) as inv1 on (inv2.id =inv1.maxid and inv2.uniqueid = inv1.uniqueid) JOIN client as c ON inv2.uniqueid = c.uniqueid
现在尝试将相同的查询转换为模型在CI中,但我不知道如何继续,因为这个包括嵌套查询与连接。有人可以帮助我吗?
答案 0 :(得分:2)
您可以使用Query Builder来创建和执行sql语句。但通常情况下,简单地使用$this->db->query('YOUR QUERY HERE')
会更有效率。
$sql = "select inv2.id,inv1.uniqueid,inv2.pastamount_due, c.name
FROM invoices as inv2
JOIN (SELECT max(id) as maxid, uniqueid from invoices GROUP by uniqueid)
as inv1 on (inv2.id=inv1.maxid and inv2.uniqueid=inv1.uniqueid)
JOIN client as c ON inv2.uniqueid = c.uniqueid";
$query = $this->db->query($sql);
if($query !== false)
{
return $query->result();
}
return NULL; //$query is false. Probably due to bad syntax in the query string