我有2张桌子: 交易表 - 处理订单的位置、金额、产品 ID、产品名称 评论 - 每个产品的评论。
我想要的是连接交易表和评论,然后在交易上显示产品名称,以及表交易中该产品的总金额,条件为状态=已完成,然后连接评论表来计算特定产品的费率。
$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();
我想要的是一个带有费率的连接表:显示产品的费率,这里的任何人都可以帮助我什么是正确的代码?
您的解决方案可能是这样的。
$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();
为了便于阅读,我已拆分了选择内容。