从 SQL 到 Laravel 8 Eloquent

Posted

技术标签:

【中文标题】从 SQL 到 Laravel 8 Eloquent【英文标题】:From SQL to Laravel 8 Eloquent 【发布时间】:2022-01-14 05:00:16 【问题描述】:

我在 SQL 中创建了一个查询,它运行良好。

SELECT learning_content_number,
            course,
            count(required) as required,
            count(overdue) as overdue,
            count(status) as status,
            count(completion_date) as completion_date

            FROM hse_leatros
            GROUP BY learning_content_number 

现在我想用 Laravel 8 Eloquent 翻译它。此脚本有效,但我缺少有关课程的信息。

$courses = Leatro::groupBy('learning_content_number')
        ->selectRaw('count(required) as required, learning_content_number')
        ->selectRaw('count(overdue) as overdue, learning_content_number')
        ->selectRaw('count(status) as status, learning_content_number')
        ->selectRaw('count(completion_date) as completion_date, learning_content_number')
        ->get();

如何在传输的代码中输入?

我的数据库表结构:

        $table->id();
        $table->integer('employee_id')->nullable();
        $table->string('course')->nullable();
        $table->string('required')->nullable();
        $table->string('mandatory')->nullable();
        $table->string('status')->nullable();
        $table->string('due_date')->nullable();
        $table->string('completion_date')->nullable();
        $table->string('overdue')->nullable();
        $table->string('learning_content_number')->nullable();
        $table->string('assigned_date')->nullable();
        $table->string('assigned_mechanism')->nullable();
        $table->string('cost_centre_id')->nullable();
        $table->string('hash')->nullable();
        $table->timestamps();
        $table->softDeletes();
   

【问题讨论】:

请提供您的表结构、测试数据和所需结果minimal reproducible example 【参考方案1】:

您只需添加->select('learning_content_number', 'course'):

$courses = $db::table('hse_leatros')
    ->groupBy('learning_content_number',  'course')
    ->select('learning_content_number',  'course')
    ->selectRaw('count(required) as required')
    ->selectRaw('count(overdue) as overdue')
    ->selectRaw('count(status) as status')
    ->selectRaw('count(completion_date) as completion_date')
    ;

echo $courses->toSql();

print_r($courses->get());

Laravel QueryBuilder online

【讨论】:

也许$courses->dd() 会做得更好,您还可以获得? 所需的值

以上是关于从 SQL 到 Laravel 8 Eloquent的主要内容,如果未能解决你的问题,请参考以下文章

从 laravel 7 升级到 laravel 8

如何将 App\Exceptions 从 laravel 7 升级到 laravel 8

从 Laravel 5.7.4 升级到 Laravel 8 的危险

如何将 laravel 版本从 8.x 降级到 7.x?

Laravel 5.8 有条件地插入 sql 片段

Laravel 模型与 POINT/POLYGON 等使用 DB::raw 表达式