晚上好,朋友们,我在找工作上有困难 SUM
从 HASMANY
与条件的关系。
我试着这样做:
$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); ?>
任何帮助都将不胜感激。
1条答案
按热度按时间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();