简体   繁体   中英

Complex paginate with NOT IN condition cakephp 2

i have a small problem to get my query work the right way.

My query should give me all lectures in the actual semester, but just those, where i'm not participating yet. So in SQL it would be:

SELECT * FROM lectures WHERE semester = $currentSemester AND lectures.id NOT IN (SELECT lectures_id FROM participaters WHERE user_id = $this->Auth->user('id'))

And what i already got is the following:

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

How can i define the condition with the user_id? Maybe someone of you can help? And sorry for my english, if here are any mistakes :)

First find a list of ids you want to exclude in the query, then use this list of ids with a condition like 'Lecture.id !=' => $ids.

Assuming you have model Participater linked to model lecture, the queries could as shown below.

//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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM