鍍金池/ 問答/PHP/ tp5 union 之后使用where 失敗

tp5 union 之后使用where 失敗

        ->alias('b')
        ->field(['(b.order_amount + b.store_amount) as total','b.create_time','b.order_id','b.pay_types'])
        ->where("b.order_status = 2")
        ->union(['select pay_amount as total,create_time,recharge_id as order_id,pay_type as pay_types from tp_recharge'])
        ->buildSql();

如上 執(zhí)行之后 sql 語句為

SELECT (b.order_amount + b.store_amount) as total,`b`.`create_time`,`b`.`order_id`,`b`.`pay_types` FROM `tp_order` `b` UNION ( select pay_amount as total,create_time,recharge_id as order_id,pay_type as pay_types from tp_recharge ) WHERE ( b.order_status = 2 )

where 條件放到最后執(zhí)行了,我想要的是 把where 條件查詢第一個表的后面,請問大家如何解決這個問題的

回答
編輯回答
苦妄

如果是tp_recharge全表的話你可以表反轉(zhuǎn)下即可

Db::table('tp_recharge')
        ->field('pay_amount as total,create_time,recharge_id as order_id,pay_type as pay_types')
        ->union(function ($query) {
            $query->alias('b')->field('(b.order_amount + b.store_amount) as total,`b`.`create_time`,`b`.`order_id`,`b`.`pay_types`')->table('tp_order')->where("b.order_status = 2");
        })
        ->buildSql();
2017年11月27日 06:51
編輯回答
傲寒

用一個中間表操作,
1.把要查詢的表各自用buildSql()生成sql ,
2.用一個中間把所有要查詢的表全部union起來,再用buildSql()生成sql。

$sqlArr[] = DB::table('tp_order')
                ->where($where)
                ->field(['(order_amount + store_amount) as total','create_time','order_id','pay_types','order_status'])
                ->buildSql();

先生成sql,多個表以此類推,要where或者其他操作都可以,要注意的是 查詢的字段都要保持一致,包括中間表

中間表把所有sql union 起來

$temp=Db::name('users')
->field("unionid as total,create_time,count(users_id) as order_id,users_name as pay_types,gift_balance as order_status")
->union($sqlArr)
->buildSql();

最后使用使用子查詢構(gòu)造新的查詢

$data = DB::table($temp.'a')
        ->where(['order_id'=>['neq',0],'create_time'=>['neq',0]])
        ->order("create_time desc")
        ->paginate($pagesize)

最后這步可以使用分頁

2017年10月1日 19:37
編輯回答
醉淸風(fēng)

這個問題,因?yàn)闆]有這種需求操作過,建議可以看下 tP5 的 where 方法源碼。不過碰到這種情況我一般會選擇用源生 sql 直接操作的。

2017年3月28日 04:28