Php Laravel-雄辩-如何汇总相关数据并查询?

Php Laravel-雄辩-如何汇总相关数据并查询?,php,laravel,eloquent,Php,Laravel,Eloquent,我在寻找数据库查询方面的帮助,而不是收集解决方案 我有以下型号: 用户 订单 产品 用户有许多订单,订单属于许多产品 在这里,我需要查询用户并选择所有已售出产品,这意味着订单所附带的所有产品数量之和 quantity值存储在order\u product透视表中 表名:用户,订单,产品&订单 理想情况下,我希望进行如下查询:例如,选择销售了至少100种产品的所有用户 DB::raw() 事先非常感谢,这已经困扰了我一段时间了 数据库模式 Schema::create('users', fun

我在寻找数据库查询方面的帮助,而不是收集解决方案

我有以下型号:

  • 用户
  • 订单
  • 产品
用户
有许多
订单,订单
属于许多
产品

在这里,我需要查询用户并选择所有已售出产品,这意味着订单所附带的所有产品数量之和

quantity
值存储在
order\u product
透视表中

表名:
用户
订单
产品
&
订单

理想情况下,我希望进行如下查询:
例如,选择销售了至少100种产品的所有用户

DB::raw()

事先非常感谢,这已经困扰了我一段时间了

数据库模式

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
});

Schema::create('orders', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id')->index();
});

Schema::create('order_product', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('order_id')->index();
    $table->unsignedBigInteger('product_id')->index();
    $table->integer('quantity')->unsigned()->default(1);
});
Schema::create('products', function (Blueprint $table) {
    $table->bigIncrements('id');
});
更新 到目前为止,我已经做到了:

\App\User::addSelect([
    'sold_products_count' => \App\Order::whereColumn('user_id', 'users.id')
                            ->join('order_product', 'orders.id', '=', 'order_product.order_id')
                            ->select(DB::raw('sum(order_product.quantity) as qty')),
])->where('users.sold_products_count', '>=', 100);
但是,最后一条语句
where('users.salled\u products\u count','>=',100)
抛出错误,因为没有
salled\u products\u count

因此,我认为我的思路是正确的,但是如何使用
where子句中的新sum列呢

我可以使用
addSelect
,还是必须使用其他工具?

最后,我解决了这个问题

答案如下:

\App\User::addSelect([
    'sold_products_count' => \App\Order::whereColumn('user_id', 'users.id')
                            ->join('order_product', 'orders.id', '=', 'order_product.order_id')
                            ->select(DB::raw('sum(order_product.quantity) as qty')),
])->having('sold_products_count', '>=', 100);

我们的想法是首先通过
addSelect
计算总和,然后我们可以使用
having
,neat

查询值。请共享表的架构,如果可能,添加示例和示例data@Aashishgaba我添加了数据库模式,如果这样更容易给出建议的话。谢谢@我已经添加了我所取得的最新进展。您能帮助我如何使用
where子句中的
addSelect
列值吗?
DB::table('users')
    ->join('orders', 'orders.user_id', '=', 'users.id')
    ->join('order_product', 'orders.id', '=', 'order_product.order_id')
    ->select('users.*', DB::raw('sum(order_product.quantity) as qty'))
    ->having('qty', '>=', 100)
    ->get();