2016-06-07 62 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()也可以。