gpt4 book ai didi

php - laravel 加入 : How can I join tables and pull various kinds of data according to my conditions form the same join?

转载 作者:行者123 更新时间:2023-11-29 16:52:34 25 4
gpt4 key购买 nike

这就是我到目前为止所做的。

DB::table('products')
->leftjoin('inventories', 'inventories.product_id', 'products.id')
})
->leftjoin('order_items as purchase_oi', function($query){
$query->on('purchase_oi.inventory_id', 'inventories.id');
$query->on('purchase_oi.status','!=', \DB::raw('"cancelled"'));
})
->select(DB::raw('sum(inventories.quantity)as qty'),
DB::raw('count(purchase_oi.inventory_id) as purchases'),
'products.id as pid', 'products.*')
->where('products.is_deleted', 0)
->where('inventories.is_deleted',0)
->groupBy('inventories.product_id')
->get();

order_items 表包含状态

enum('shipped','return''cancelled');

此问题出现在与 order_items 表的联接上。目前,我只是获取不等于已取消的数据,但我想获取返回的 order_items 数据和已取消的 order_items 数据。即从 order_items 表中获取购买、取消和返回计数。预期输出为:

0=>purchases = 4,
returns = 10,
cancelled = 2

最佳答案

我认为问题出在你的groupBy()上。如果您有以下查询:

SELECT COUNT(*) AS count FROM table GROUP BY id

不会最终得到

+-------+
| count |
+-------+
| 5 |
+-------+

相反,你最终会得到:

+-------+
| count |
+-------+
| 1 |
+-------+
| 1 |
+-------+
| 1 |
+-------+
| 1 |
+-------+
| 1 |
+-------+

每个分组分组的所有项目数。

试试这个:

\DB::enableQueryLog();
\DB::flushQueryLog();

//Execute your query

$queries = /DB::getQueryLog();
/DB::disableQueryLog();
/DB::flushQueryLog();

$queries = collect($queries)->map(function (array $query) {
return array_only($query, ['query', 'bindings']);
})->toArray();

dd($queries);

这应该告诉您正在执行什么 SQL。

关于php - laravel 加入 : How can I join tables and pull various kinds of data according to my conditions form the same join?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52740658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com