如何在laravel上用where in hasmany relationship生成sum()?感谢您的帮助

szqfcxe2  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(426)

晚上好,朋友们,我在找工作上有困难 SUMHASMANY 与条件的关系。
我试着这样做:

$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 价值观。我试着把它放在 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); ?>

任何帮助都将不胜感激。

hwamh0ep

hwamh0ep1#

你想做的事可以用 withCount 还有一个 Closure ```
$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();

相关问题