【问题标题】:using sum with relation Laravel Eloquent ORM使用 sum 与关系 Laravel Eloquent ORM
【发布时间】:2020-03-25 11:32:30
【问题描述】:

我有模型材料,它有

 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();
    });

我想以另一种方式获取(材料不足)选择所有材料表格材料表,其中所有成本价格表的数量总和

【问题讨论】:

  • 看看whereHaslaravel.com/docs/6.x/…
  • 当我使用$materials = Material::whereHas('costPrices', function($q) { $q->havingRaw('SUM(quantity) > 4'); })->get(); 时出现错误SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression

标签: sql laravel eloquent orm


【解决方案1】:

你有两个选择:

您可以通过添加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() 在大量行上更快。

【讨论】:

    猜你喜欢
    • 2015-04-04
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2023-03-14
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多