2017-07-18 67 views
0

我目前的MySQL查詢是CakePHP的3.4 MySQL來ORM轉換

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; 

我目前的ORM是繼我只是無法在

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

你在問如何創建(和/或傳遞)子查詢嗎? – ndm

回答

0

處理選擇部分找到答案 ITS「SUB-查詢「

$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']);