在codeigniter查询生成器中使用union,并在虚拟mysql列中进行过滤

时间:2018-03-05 05:21:35

标签: mysql database codeigniter activerecord query-builder

在我的项目中,我使用带有服务器端处理的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)

但是这会返回我没有任何列名称来源,如何过滤此列?

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

有一种方法可以做到这一点,但有点 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);