无法从belongsstomany表

时间:2017-01-21 07:56:46

标签: cakephp cakephp-3.x

我无法从下面的主题表中获取任何字段来显示。我得到了正确的学生数据,我没有错误,但我没有从主题表中获得任何字段。不确定我做错了什么。如果我删除where子句,我会从主题中获取所有数据,因此问题是包含中的where子句。

      $students = $this->Students->find()
                  ->contain([ 'Subjects' => function ($q) {
                      return $q
                           ->select(['id','name'])
                            ->where(['Subjects.id >' =>60])  ;  
                            }])   
                  ->select(['Students.id','Students.last_name','Students.first_name'])
                  ->where(['Students.student_inactive'=>false])
                    ->hydrate(true);


             foreach($students as $key=>$item2):
                    debug($item2);
             endforeach;


    /////////output
object(App\Model\Entity\Student) {

    'id' => (int) 24,
    'last_name' => 'Test',
    'first_name' => 'Cavr',
    'subjects' => [],
    '[new]' => false,
    '[accessible]' => [
        '*' => true
    ],
    '[dirty]' => [],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Students'

}
....

1 个答案:

答案 0 :(得分:0)

 $sub = $this->Students->find()
            // ->contain(['Subjects'])
              ->select(['Students.id'])
               ->where(['Students.student_inactive'=>0 
                   ])
              ->order(['Students.first_name' => 'ASC'])
              ->hydrate(true);

我需要使用匹配,并且还要调用students_subjects表subject_students来获取某些ODD原因

          $sub->matching('Subjects', function ($q) use ($subId) {

                 return $q
                   ->select(['Subjects.id','Subjects.name'])
                  ->where(['Subjects.id >' =>$subId]);
                });