Home > Software engineering >  From SQL to Laravel 8 Eloquent
From SQL to Laravel 8 Eloquent

Time:12-09

I have created a query in SQL and it works quite well.

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 

Now I want to translate it in Laravel 8 Eloquent. This script works, but I am missing the information about the course.

$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();

How can I enter the in the code that it is transferred with?

My DB-Table structur:

        $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();
   

CodePudding user response:

You need just add ->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

  • Related