1

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 now I'm trying find() on Image->find('all', $params); with no luck.

1
  • That query won't work anyway, you're not looking at the join tables at all. Commented Mar 24, 2011 at 15:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanx alot! Exactly what I was looking for:) I'll have a look at the documentation.
Insted of binding the model in the controller, you can also do it in the model using: var $hasOne = 'ImagesUnit'; Which means you can skip that first line: $this->Image->bindModel(array('hasOne' => array('ImagesUnit')));
Oh yeah, indeed. There are a few 'best practices' that I've come up with (not necessarily the community's best practices), and one of them is to define such association in the model and never bind it on the fly. If you need to deal with a model that is not associated, then you can use the loadModel method. And I always recommend to drop the recursive functionality and opt instead for the Containable behavior. This ebook explains this Containable technique.
I just realized that the link to downloading the e-book is broken. Here is a new link: pseudocoder.com/Super_Awesome_Advanced_CakePHP_Tips.pdf
0

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.

1 Comment

Tried that, gave med "SQL Error: 1054: Unknown column 'Unit.id' in 'where clause'" on Query: SELECT Image.id, Image.name, Image.url FROM images AS Image WHERE Unit.id = 30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.