Laravel 用 where 求和,用 Eloquent 求别名

Laravel Sum with where and alias with Eloquent

我有一个旧的 Codeigniter 项目查询:

$this->db->select("SUM(source = 'FBS) AS facebook");
$this->db->select("SUM(source = 'FBS' AND promotion = 0) AS facebook_promotion");
$this->db->select("SUM(source = 'IG') AS instagram");
$this->db->select("SUM(source = 'LP') AS landing_page");   

我希望使用 Laravel 获得相同的结果,如果可能的话,使用 Eloquent 而不是查询生成器或原始查询。

如果你想使用原始查询生成器,就像,

DB::table('table_name')->where('source','=','FBS')->sum('source');

对于 Eloquent 个模型,

 Model::where('source','=','FBS')->sum('source')

它也适用于 eloquent 关系。

此外,对于像您这样的多个总和结果,它会像,

DB::table('table_name')->get( array(
  DB::raw("SUM(source = 'FBS) AS facebook"),
  DB::raw("SUM(source = 'FBS' AND promotion = 0) AS facebook_promotion"),
));

使用DB::raw;

以这种方式解决
$data = CONTACT::select(
    DB::raw('DATE_FORMAT(created_at, "%m-%d-%Y")),
    DB::raw('SUM(source = "IG") as instagram'),
    DB::raw('SUM(source = "FBS") as facebook')
)
->orderBy('data', 'DESC')
->groupBy(DB::raw("DATE_FORMAT(created_at, '%d-%m-%Y')"))
->get();
return response()->json(['success' => $data], 200);