2016-06-07 65 views
1

我正在將一些發現從cakephp2轉換爲cakephp3。 我需要搜索存儲在不同列上的導師表上的名字和姓氏。根據文檔,我需要在表格之間加入左連接。我已經使用了2個字段的條件,但是如果兩個參數都有一個值,那麼它和'和'條件一樣。 我的問題是在CakePHP 3中生成OR SQL語句

q1) I cant get the data with just the first name only , and the surname is null. 
    q2) I need to pass both first name and surname to get just those data with that name. 
     Not sure how to do this in cakephp3. 

eg $a5='fred'; //just want all first names like fred 
    $a6=null; //sometimes this will be filled 
    $a3='2015-05-30'; 
    $a4='2016-06-01'; 

$query3 = $this->Lessons->find() 
      ->contain(['Tutors']) 
      ->select(['lessons.id','lessons.lesson_date','tutors.id','tutors.first_name','tutors.last_name' ])  
      ->where(['Lessons.lesson_date >' => $a3,'Lessons.lesson_date <' => $a4, 
'OR' => [['tutors.first_name like' => '%'.$a5.'%'], ['tutors.last_name like' => '%'.$a6.'%']], 

     ]); 

     foreach ($query3 as $row) { 

        debug($row->toArray()); 


      } 

我不明白這一點的文檔。 http://book.cakephp.org/3.0/en/orm/query-builder.html#advanced-conditions

更新 - 嘗試這一點,這也只是給所有的數據與'at'或'to',但它應該是任何名稱都'at'和'to'在他們。

$query3 = $this->Lessons->find() 
      ->contain(['Tutors','Subjects', 'TutoringTypes','Terms','Students']) 
       ->select(['lessons.id','lessons.lesson_date','tutors.id','tutors.first_name','tutors.last_name', 
        'subjects.id','subjects.name','terms.id','terms.title'])   
    ->where(['Lessons.lesson_date >' => $a3,'Lessons.lesson_date <' => $a4]) 
    ->orWhere(function ($exp) { 
     return $exp->and_([ 
      'tutors.first_name like' => '%an%', 
      'tutors.last_name like' => '%to%', 
     ]); 
    }); 

回答

1

注意生成的SQL。您可以在DebugKit中看到它或通過調用$query->sql()進行調試。您正在構建錯誤的查詢:

您生成OR ((... AND ...)),因爲您使用的是and_。你可能想要... OR ...

->orWhere(function ($exp) { 
    return $exp->and_([ 
     'tutors.first_name like' => '%an%', 
     'tutors.last_name like' => '%to%', 
    ]); 
}); 

您可能想要OR。但直接將數組傳遞給orWhere()也可以。