在codeigniter查询生成器中使用union,并在虚拟mysql列中进行过滤
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在codeigniter查询生成器中使用union,并在虚拟mysql列中进行过滤相关的知识,希望对你有一定的参考价值。
在我的项目中,我使用带有服务器端处理的datatables插件。它工作正常,直到我进行搜索或订单(排序)操作,因为它需要活动记录来做到这一点。
我的情况是,我有一个帐户表,收入表和支付表,我想查看收入和支付表的所有数据,这就是我需要工会的原因。我的查询如下---
SELECT 'Income' as source, fld_type, fld_amount, ta.fld_account as account, fld_date, tbl_revenue.fld_description as fld_traninfo, tbl_revenue.fld_created as created
FROM tbl_revenue JOIN tbl_accounts as ta on tbl_revenue.fld_account_id = ta.fld_id
UNION
SELECT 'Expense' as source, fld_type, fld_amount, tae.fld_account, fld_date, tbl_payment.fld_description as fld_traninfo, tbl_payment.fld_created as created
FROM tbl_payment JOIN tbl_accounts as tae on tbl_payment.fld_account_id = tae.fld_id
有没有办法在此查询中使用查询生成器?
第二个问题,你可以看到我创建了一个名为'source'的虚拟列,我想使用where子句过滤此列,并附加此查询,如下所示
WHERE source like "%a%" limit(10,0)
但是这会返回我没有任何列名'source',我该如何过滤此列?
任何帮助表示赞赏。
答案
有一种方法可以做到这一点,但它有点hacky因为codeigniter的querybuilder在查询中添加了一个自动SELECT
语句,如果你没有自己指定它
为了获得您想要的内容,您需要在2个查询中拆分select语句,并将where子句添加到此查询中
这样的东西应该工作:
$strQuery1 = $this->db
->select('income as source, fld_type, fld_amount, ta.fld_account as account, fld_date, tbl_revenue.fld_description as fld_traninfo, tbl_revenue.fld_created as created')
->from('tbl_revenue')
->join('tbl_accounts as ta', 'tbl_revenue.fld_account_id = ta.fld_id')
->get_compiled_select();
$strQuery2 = $this->db
->select('Expense as source, fld_type, fld_amount, ta.fld_account as account, fld_date, tbl_revenue.fld_description as fld_traninfo, tbl_revenue.fld_created as created')
->from('tbl_payment')
->join('tbl_accounts as ta', 'tbl_revenue.fld_account_id = ta.fld_id')
->get_compiled_select();
$strWhere = substr($this->db->like('source', 'a', 'both')->get_compiled_select(), 8);
$query = $this->db->query($strQuery1.' UNION '.$strQuery2.$strWhere);
以上是关于在codeigniter查询生成器中使用union,并在虚拟mysql列中进行过滤的主要内容,如果未能解决你的问题,请参考以下文章
如何在 CodeIgniter 中为 is_unique 表单验证启用查询生成器?