我有一个小问题,无法让我的查询以正确的方式工作。
我的查询应该为我提供实际学期的所有讲座,但仅限于我尚未参加的讲座。所以在 SQL 中它将是:
SELECT * FROM lectures WHERE semester = $currentSemester AND lectures.id NOT IN (SELECT lectures_id FROM participaters WHERE user_id = $this->Auth->user('id'))
我已经得到的是以下内容:
$this->paginate = array(
'conditions' => array(
'Lecture.semester >=' => $currentSemester,
'not' => array(
'Lecture.id' => array(
),
),
),
'order' => array(
'Lecture.name' => 'asc',
),
'contain' => array(
'Participater',
),
);
$this->set('lectures', $this->paginate($this->Lecture));
如何使用 user_id 定义条件?也许你们中有人可以帮忙?如果有任何错误,我的英语很抱歉:)
最佳答案
首先找到要在查询中排除的 ID 列表,然后使用此 ID 列表以及“Lecture.id !=” => $ids 等条件。
假设您有模型参与者链接到模型讲座,查询可能如下所示。
//retrieve the list of excluded ids
$excluded_ids = $this->Lecture->Participater->find('list',array(
'conditions' => array(
'Participater.user_id' => $this->Auth->user('id')
),
'fields' => array('lecture_id')
);
$this->paginate = array(
'conditions' => array(
'Lecture.semester >=' => $currentSemester,
'Lecture.id !=' => $excluded_ids,//put the excluded ids here
),
'order' => array(
'Lecture.name' => 'asc',
),
'contain' => array(
'Participater',
),
);
$this->set('lectures', $this->paginate($this->Lecture));
关于php - 复杂分页与 NOT IN 条件 cakephp 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26514676/