【问题标题】:How to make a SUM() with WHERE in HASMANY relationship on laravel? Any help is appreciated如何在 laravel 的 HASMANY 关系中使用 WHERE 生成 SUM()?任何帮助表示赞赏
【发布时间】:2020-08-03 22:35:32
【问题描述】:

朋友们晚上好,我很难从有条件的 HASMANY 关系中获得 SUM

我试图做这样的事情:

$marketPlaces = ModelAccountMarketplace::with(['orders'])
->whereHas('orders', function ($query) use ($dates) {
    $query->selectRaw('SUM(valor_frete) as somaFreteGratis')
          ->whereBetween('datetime', [$dates['dateStart'], $dates['dateEnd']]);
});

但是当我尝试通过以下方式获取价值时:var_dump($marketPlace->somaFreteGratis);

我得到一个null 值。我尝试将 where 放在 WITH() 中,例如:

$marketPlaces = ModelAccountMarketplace::with(['orders' => function ($query) {
    $query->selectRaw('SUM(valor_frete) as somaFreteGratis')->where('tipo_frete', 'gratis');
}])
->whereHas('orders', function ($query) use ($dates) {
    $query->whereBetween('datetime', [$dates['dateStart'], $dates['dateEnd']]);
});

但是在每次尝试检查时,我都会得到一个空值:

<?= var_dump($marketPlace->somaFreteGratis); ?>

任何帮助将不胜感激。

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    您可以使用withCountClosure 来完成您想要做的事情

    $marketPlaces = ModelAccountMarketplace::withCount([
        'orders as somaFreteGratis' => function ($query) use ($dates) {
            $query->select(DB::raw('sum(valor_frete)')
            ->where('tipo_frete', 'gratis')
            ->whereBetween('datetime', [$dates['dateStart'], $dates['dateEnd']]);
        }
    ])
    ->get();
    

    【讨论】:

    • 我也试过这个,但由于某种原因,当我尝试使用 $marketPlaces[0]->somaFreteGratis 时返回 0 ......并且 mysql 上有 2 行 valor_frete 其中tipo_frete = gratis,但感谢您的帮助
    • 抱歉,为具有tipo_frete = 免费的订单的市场返回整数1,但应该返回浮点值的总和,对吧?
    • 此查询返回所有市场及其 someFreteGratis。如果您想要一个特定的市场,请尝试将-&gt;get() 替换为-&gt;find(id)。然后就可以直接用$marketPlaces-&gt;somaFreteGratis访问了
    猜你喜欢
    • 2022-11-24
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多