我遇到以下代码的问题:
public function index() {
$qObj = \DB::table('customers as c')
->join('companies_has_customers as chc', 'chc.comhc_cus_id', '=', 'c.cus_id')
->join('cuscategory as cc', 'chc.comhc_cca_id', '=', 'cc.cca_id')
->join('transactions as t','t.trn_cus_id', '=','c.cus_id')
->select('t.trn_id');
$qObj->where('comhc_com_id', '=', $this->companyId);
$res = array(
'count' => $qObj->count(),
'items' => $qObj->get()
);
//print_r($this->showLastQuery());
return parent::prepareResponse($res, 200, 'customers');
}
这段代码产生以下SQL查询:
select * from `customers` as `c`
inner join `companies_has_customers` as `chc` on `chc`.`comhc_cus_id` = `c`.`cus_id`
inner join `cuscategory` as `cc` on `chc`.`comhc_cca_id` = `cc`.`cca_id`
inner join `transactions` as `t` on `t`.`trn_cus_id` = `c`.`cus_id`
where comhc_com_id` = 1
问题:
为什么QueryBuilder会按照上面的语法生成select *...
而不是select t.trn_id...
?
答案 0 :(得分:2)
更改顺序:
$res = array(
'items' => $qObj->get(),
'count' => $qObj->count()
);
它会起作用。
但更好的是,不要两次查询数据库,而是执行此操作:
$items = $qObj->get();
$res = array(
'items' => $items,
'count' => count($items)
);
您的代码的问题是count()
方法行为 - 它会重置columns
属性(使用select
设置),这就是全部。
答案 1 :(得分:1)
将它放在$qObj->get(['t.trn_id'])
中,如下所示:
$res = array(
'items' => $items = $qObj->get(['t.trn_id']),
'count' => count($items) // count the cached $items
);
而不是select
(删除select('t.trn_id')
)。