如何将本机 PHP7 转换为查询 eloquent Laravel?

How can I convert native PHP7 into query eloquent Laravel?

我正在从 php 7 迁移到 laravel,但无法完成查询。如何像下面的例子解决数据查询

$年份=日期('Y'); $月 = 日期('m');

select id, tglupload, 
substring(CONVERT(varchar,tglupload,106),4,2) date, 
COUNT(1) as Totalemployeall
from [MS_SK] 
where substring(CONVERT(varchar,tglupload,106),4,2) = $month
and substring(CONVERT(varchar,tglupload,106),7,4) = $year
AND (status_allow <> 'NOTALLOW' OR status_allow is null)
GROUP BY rollup(id, tglupload)
order by id ASC

不幸的是,您必须为此使用原始查询。但是您可以使用 Laravel's scope function.

使您的查询更好

例如在你的模型中(与table相关的模型[MS_SK])你可以添加以下2个作用域函数:

class YourModel extends Model {

    public function scopeFiltrateTglUpload($query, int $month=null, int $year=null)
    {
        $year = $year ?? date('Y');
        $month = $month ?? date('m');

        return $query->where(\DB::raw("substring(CONVERT(varchar,tglupload,106),4,2)", "=", $month))
            ->where(\DB::raw("substring(CONVERT(varchar,tglupload,106),7,4)", "=", $year));
    }

    public function scopeTheStatusIsNullOrNotAllowed($query)
    {
        return $query->where(function($subQuery) {
            $subQuery->where('status_allow', '<>', 'NOTALLOW')
                ->orWhereNull('status_allow');
        });
    }

}

那么您就可以按照下面的方式使用它们了:

$result = YourModel::selectRaw('
        `id`, `tglupload`, 
        substring(CONVERT(varchar,tglupload,106),4,2) `date`, 
        COUNT(1) as `Totalemployeall`
    ')
    ->filtrateTglUpload()
    ->theStatusIsNullOrNotAllowed()
    ->groupBy(\Db::raw('rollup(id, tglupload)'))
    ->orderBy('id')
    ->get();

请注意,这只是一个示例,供您参考。然后你应该让它工作:)如果你需要任何帮助,请在评论中告诉我。