how to get CakePHP many-to-many result
I have a many-to-many relation between the models Image and Units using a images_units join table.
How can I translate this query to a cakePHP find()?
SELECT * FROM Image, Units, images_units WHERE images_units.unit_id = 29;
Right 开发者_StackOverflow中文版now I'm trying find() on Image->find('all', $params); with no luck.
Straight from the CakePHP Manual:
$this->Image->bindModel(array('hasOne' => array('ImagesUnit')));
$this->Image->find('all', array('fields' => array('Image.*'),'conditions' => array('ImagesUnit.unit_id' => 29)));
Of course, you will need to have the HABTM association defined in the model. See the whole section on HABTM for learning how to use it.
In your Image Model, add the following code:
$hasAndBelongsToMany = 'Unit';
The find()
in your Images
controller should look like this:
$this->Image->find('all', array('conditions'=>array('Unit.id'=>29)));
Still not quite sure this is what you're looking for but I think this is correct.
精彩评论