查询计数也是非匹配值

时间:2018-05-08 11:47:43

标签: mysql laravel-5 eloquent

我有这个返回匹配值的查询。

Availability::select(DB::raw('count(start) as count,start'))
                                    ->whereIn('start', [100,200,300,400])
                                    ->groupBy('start')
                                    ->get();

并返回:

count | start
1     | 100
2     | 200

我希望结果中的节目也是0计数值。像:

count | start
1     | 100
2     | 200
0     | 300
0     | 400

dd(),其中日期为值。 [' 2018-09-10',' 2018-09-18',' 2018-09-16',' 2018-09-15&# 39;]

array:1 [▼
  0 => array:2 [▼
    "count" => 1
    "start" => "2018-09-10"
  ]
]

有什么想法吗? 在此先感谢:)

2 个答案:

答案 0 :(得分:1)

因此,使用集合可以执行以下操作:

在数组/集合中定义开始日期

$dates = collect(['2018-09-10', '2018-09-18', '2018-09-16', '2018-09-15']);

您可以在whereIn('start', $dates)

中使用此功能
$result = Availability::...
$collection = $dates->map(function($item) use($result) {
    return ['count' => $result->firstWhere('start', $item)['count'] ?? 0, // in case line does not work use optional($result->firstWhere('start', $item))->count ?? 0, 
            'start' => $item];
});

dd($collection); // your desired result

我和修补匠一起玩,所以这是最后的修补课程:

>>> $a = collect([['count' => 1, 'start' => '2018-09-10'], ['count' => 3, 'start' => '2018-09-11']])
=> Illuminate\Support\Collection {#828
     all: [
       [
         "count" => 1,
         "start" => "2018-09-10",
       ],
       [
         "count" => 3,
         "start" => "2018-09-11",
       ],
     ],
   }
>>> $b = collect(['2018-09-10', '2018-09-11', '2018-10-14'])
=> Illuminate\Support\Collection {#809
     all: [
       "2018-09-10",
       "2018-09-11",
       "2018-10-14",
     ],
   }
>>> $b->map(function($item) use($a) {return ['count' => $a->firstWhere('start', $item)['count'] ?? 0, 'start' => $item];});
=> Illuminate\Support\Collection {#832
     all: [
       [
         "count" => 1,
         "start" => "2018-09-10",
       ],
       [
         "count" => 3,
         "start" => "2018-09-11",
       ],
       [
         "count" => 0,
         "start" => "2018-10-14",
       ],
     ],
   }
>>>

答案 1 :(得分:0)

您可以使用需要与(100,200,300,400)进行比较的变量创建一个额外的表。然后你可以加入并计算。

它不漂亮,但是你有一个例子:http://sqlfiddle.com/#!9/3f906c/1