如何在月份中从null获取数据- laravel

dfty9e19  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(133)

我试图在MySQL数据库中获取数据,所以我想得到所有的数据,即使日期字段为空,这是我的代码

$prod = DB::table('daily_enters')
                ->leftJoin('daily_inputs', 'daily_enters.daily_input_id', '=', 'daily_inputs.id')
                ->select('daily_inputs.date',DB::raw('sum(daily_enters.crops) as crops_actual'))
                ->whereIn('daily_inputs.date', $dates)
                ->where('daily_inputs.divisi', 'A')
                ->groupBy('daily_inputs.date','daily_inputs.divisi')
                ->get();

这就是结果

^ Illuminate\Support\Collection {#1403 ▼
  #items: array:30 [▼
    0 => {#1402 ▼
      +"date": "2022-01-02"
      +"crops_actual": 353.91
    }
    1 => {#1407 ▼
      +"date": "2022-01-03"
      +"crops_actual": 465.2
    }
    2 => {#1405 ▶}
    3 => {#1406 ▶}
    4 => {#1410 ▶}
    5 => {#1408 ▶}
    6 => {#1409 ▶}
    7 => {#1412 ▶}
    8 => {#1413 ▶}
    9 => {#1411 ▶}
    10 => {#1414 ▶}
    11 => {#1415 ▶}
    12 => {#1416 ▶}
    13 => {#1417 ▶}
    14 => {#1418 ▶}
    15 => {#1419 ▶}
    16 => {#1420 ▶}
    17 => {#1421 ▶}
    18 => {#1422 ▶}
    19 => {#1423 ▶}
    20 => {#1424 ▶}
    21 => {#1425 ▶}
    22 => {#1426 ▶}
    23 => {#1427 ▶}
    24 => {#1428 ▶}
    25 => {#1429 ▶}
    26 => {#1430 ▶}
    27 => {#1431 ▶}
    28 => {#1432 ▶}
    29 => {#1433 ▶}
  ]
  #escapeWhenCastingToString: false
}

返回了每月31天的数据,但未找到2022-01-01,因为其没有数据,但在这种情况下,我想显示“2022-01-01”,数据返回= 0
所以如果你对这个问题有什么想法,请告诉我正确的解决方法。谢谢

njthzxwz

njthzxwz1#

我认为最好让laravel处理日期范围,例如使用
第一个月
对于现有查询,您将得到add ->get()->keyBy('daily_inputs.date');
之后,只需循环$dateRange

foreach ($dateRange as $range) {
   $date = $range->format('Y-m-d');
   var_dump(isset($prod[$date]) ? $prod[$date] : null)
}

希望这对你有帮助。
注意:正如@takumabo提到,您还可以使用laravel helper data_get()

$item = data_get($prod, $date);
var_dump($item ?? null)

如果daily_inputs. date类型为datetime,则可以在将其用作键时对其进行格式化

->get()->keyBy(function ($record) { 
  return $record->date->format('Y-m-d');
});

相关问题