繁体   English   中英

使用 sum 与 Laravel Eloquent ORM 的关系

[英]using sum with relation Laravel Eloquent ORM

我有模型材料

 protected $with = ['costPrices'];

public function costPrices(){
    return $this->hasMany(CostPrice::class);
}

cost_prices 表有多个数量

 //create_cost_prices_table
   Schema::create('cost_prices', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('material_id');
        $table->unsignedBigInteger('supplier_id');
        $table->integer('quantity');
        $table->timestamps();
    });

我想以另一种方式获得(材料不足)从材料表中选择所有材料,其中 cost_prices 表的所有数量的总和 < 3 并给我结果材料而不是计数

您有 2 个选择:

您可以通过添加selectgroupBy使用whereHas()修复您的选项:

$materials = Material
    ::whereHas('costPrices', function($q) { 
        $q
            ->select('meterial_id')
            ->groupBy('material_id')
            ->havingRaw('SUM(quantity) > 4'); 
    })
    ->get();

或者使用子查询:

对于 Laravel 6.x:

$materials = Material
    ::addSelect([
        'cost_prices_sum' => CostPrice::selectRaw('sum(quantity)')->whereColumn('material_id', 'material.id')
    ])
    ->having('cost_prices_sum', '>', 4)
    ->get();

对于 Laravel 5.x:

$materials = Material
    ::selectRaw('carts.*, (select sum(quantity) from cost_prices where cost_prices.matrerial_id = meterials.id) as cost_prices_sum')
    ->having('cost_prices_sum', '>', 4)
    ->get();

更新: whereHas()选项在大量行上速度更快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM