连接两个表并使用 where 条件 laravel 获取总和和平均费率

问题描述 投票:0回答:1

我有2张桌子: 交易表 - 处理订单的位置、金额、产品 ID、产品名称 评论 - 每个产品的评论。

我想要的是连接交易表和评论,然后在交易上显示产品名称,以及表交易中该产品的总金额,条件为状态=已完成,然后连接评论表来计算特定产品的费率。

transaction table

reviews table

RAting table and Product

$join = DB::table('transactions')->select('transactions.productid')->selectRaw('SUM(transactions.amount) as totalamount')->join('reviews','transactions.productid', '=', 'reviews.productid')->where('transactions.busid', '=', $user)->where('transactions.status', '=', 'Completed')->groupBy('transactions.productid')->get();

我尝试过,但它没有显示 PR0001 - 1255 的正确总金额

此代码可以工作,但它没有连接:

        $topProduct = Transaction::where('busid', $user)->select([DB::raw('SUM(amount) as amount'), DB::raw('productname as productname'), (DB::raw('count(productid) as prodcount'))])
            ->where('status', 'completed')->groupBy('productname')->orderBy('amount', 'desc')->get();

我想要的是一个带有费率的连接表:显示产品的费率,这里的任何人都可以帮助我什么是正确的代码?

laravel join eloquent phpmyadmin where-clause
1个回答
0
投票

您的解决方案可能是这样的。

$results = Transaction::query()
        ->select('productId, productname')
        ->selectRaw('SUM(amount) as amount')
        ->selectRaw('COUNT(productid) as prodcount')
        ->selectRaw('COUNT(DISTINCT orderid) as amount_of_orders')
        ->selectSub(
            Review::query()
                ->selectRaw('AVG(rate)')
                ->whereColumn('reviews.productid', 'transactions.productid'),
            'avg_rating'
        )
        ->where('busid', $user)
        ->where('status', 'completed')
        ->groupBy('productId')
        ->orderBy('amount', 'desc')
        ->get();

为了便于阅读,我已拆分了选择内容。

  1. 我们使用不同的计数来计算按产品分组的唯一订单。因此,如果一个订单有两次相同的产品,则只计算一件。
  2. 我们使用子查询来获取产品的平均费率。该函数的第二个参数将是该列的名称。
© www.soinside.com 2019 - 2024. All rights reserved.