问题
I've googled around for this, but part of the problem is that I'm not really sure how to concisely describe my problem. I have two relevant models here: Application and Absence. Application belongsTo Absence, Absence hasMany Application. Here's the schema for Application:
CREATE TABLE applications (
id int unsigned AUTO_INCREMENT PRIMARY KEY,
user_id int unsigned,
absence_id int unsigned
);
It's pretty simple. I want to paginate all Absences with an Application from a particular user (I'm doing this in the Absences controller). I can get close with this code:
absences_controller.php:
$this->paginate = array(
'contain' => array(
'Application' => array(
'conditions' => array(
'Application.user_id' => $viewer_id,
//'NOT' => array('Application.id' => null),
)
),
)
);
$this->set('absences', $this->paginate());
This does return the Absences I want, but it also returns all Absences that have no Application associated with them. Is there a way to do this without custom queries? I'd like to keep my app Cakey. You can see one of my attempts to strip the null Application results in the commented-out 'NOT' line in the code.
Thanks!
回答1:
You are facing the normal Containable behavior.
What you are doing is retreiving all Absence, and join application if Application.user_id = $viewer_id. You are not returning only the absences related to your user.
The simplest way to get what you want is retreiving your data from the Application point of view and joining the Absence model.
In applications_controller.php
$this->set('applications', $this->paginate('Application' => array('conditions' => array('Application.user_id' => $viewer_id))));
回答2:
Try:
$this->paginate = array(
'conditions' => array(
'Absence.application_id >' => 0
),
'contain' => array(
'Application' => array(
'conditions' => array(
'Application.user_id' => $viewer_id
)
),
)
)
回答3:
Try this..
$this->paginate = array('Application' => array('conditions' => 'Application.user_id' => $viewer_id));
来源:https://stackoverflow.com/questions/8704445/cakephp-eliminating-null-results-from-pagination