290 laravel中的子查询

可以怎么写

$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery()) 
->count();
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder as QBuilder;
//上面是引用类,为区别于Eloquent\Builder,重命名为QBuilder
//下面的是构建查询的核心代码
        //要点:用于构造子查询的临时表,无get方法
        $temp_a=DB::table('erp_orders_detail as items')
            ->leftJoin('erp_orders as orders','items.order_id','=','orders.id')
            ->leftJoin('erp_product as product','product.id','=','items.product_id')
            ->leftJoin('erp_product_category as cate','cate.product_id','=','items.product_id')
            ->where('orders.status','=',4)
            ->selectRaw('orders.order_code,items.quantity as item_quantity,items.product_id,items.id as item_id,product.sku,product.cn_name,sum(case cate.category_id when 26 then 1 else 0 end) self')
            ->groupBy('items.id');
        $temp_b=DB::table('erp_inventory as inventory')
            ->rightJoinSub($temp_a,'table_a',function(QBuilder $query){
                $query->on('inventory.product_id','=','table_a.product_id');
            })
            ->selectRaw('table_a.*,sum( inventory.quantity ) in_quantity,sum( inventory.quantity_lock ) in_quantity_lock ')
            ->groupBy('table_a.item_id');
        $result=DB::table('erp_inventory as inven')
            ->rightJoinSub($temp_b,'table_b',function(QBuilder $query){
                $query->on('inven.product_id','=','table_b.product_id');
            })
            ->selectRaw('table_b.*,sum( CASE inven.warehouse_id WHEN 1 THEN inven.quantity ELSE 0 END ) dg_quantity')
            ->groupBy('table_b.item_id')
            ->orderByDesc('self')
            ->get();

相信上面的已经可以解决大部分问题!
官方文档
在这里插入图片描述
参考链接:https://laravel.com/docs/5.8/queries#raw-expressions
https://blog.csdn.net/weixin_44107914/article/details/102745807
https://zhuanlan.zhihu.com/p/65673620
https://learnku.com/docs/laravel/8.x/queries/9401#b5bee6

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

phpstory

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值