0

my Current MYSQL query is

SELECT
    cl.user_id,
    COUNT(q.id) as completed_questions,
    (
        SELECT
            SUM(points) 
        FROM
            completed_levels 
        WHERE
            user_id = cl.user_id 
    )
    as level_point 
FROM
    completed_levels cl 
    JOIN
        questions q 
        on q.level_id = cl.level_id 
GROUP BY
    cl.user_id;

my current ORM is following i just not able to handle select part in

$completedLevels = TableRegistry::get('CompletedLevels');
$completedLevels = $completedLevels->find('All');
$completedLevels = $completedLevels
    ->contain(['Users', 'Levels'])
    ->select([
        'user_name' => 'Users.name',
        'count_questions' => 'COUNT(Questions.id)',
        'total_pints' => [
            'select'=>'SUM(CompletedLevels.points)'
        ]
    ])
    ->join([
        'table' => 'Questions',
        'conditions' => 'Questions.level_id = CompletedLevels.level_id',
    ])
    ->group(['CompletedLevels.user_id'])
    ->all();
ndm
  • 59,784
  • 9
  • 71
  • 110
Noman iqbal
  • 71
  • 1
  • 8

1 Answers1

0

Found answer ITS "SUB-Query"

    $completedLevels = TableRegistry::get('CompletedLevels');
    TableRegistry::config('cl', ['table' => 'completed_levels']);
    $cl = TableRegistry::get('cl');
    $cl = $cl->find('all');
    $cl ->select($cl->func()->sum('points'));

    $completedLevels = $completedLevels->find('All');
    $completedLevels = $completedLevels
        ->contain(['Users', 'Levels'])
        ->select([
            'user_name' => 'Users.name',
            'count_questions' => 'COUNT(Questions.id)',
            'total_pints' => $cl->where('user_id = CompletedLevels.user_id')
        ])->join([
            'table' => 'Questions',
            'conditions' => 'Questions.level_id = CompletedLevels.level_id',
        ])->group(['CompletedLevels.user_id']);
Noman iqbal
  • 71
  • 1
  • 8