0

I have a gallery model that has many photos, and in my gallery view I'm finding the gallery by $slug. I'm displaying all the photos that belong to a specific gallery_id. This is working as expected.

However, I'd like to add a condition to the query that only returns the photos if the photo.active => 'yes'.

What I'm finding is that because the gallery view is found by $slug, my attempts to filter the photos isn't working. In the photos model I save the gallery_id and not the gallery.slug.

I've tried to use containable in the gallery controller but I'm getting the following errors when using this controller find:

    $galleryphotos = $this->Gallery->Photo->find('all', array(
    'contain' => array('Photo'),
    'conditions' => array(
        'gallery.slug'=> $slug,
        'photo.active'=>'yes')));   

Error I get in the view:

Warning (512): Model "Photo" is not associated with model "Photo"

Is adding a gallery.slug column to the photos model the best way to query photos with conditions?

Also, why do I get the error when using containable in the gallery controller?

Cheers, Paul

Paul
  • 237
  • 5
  • 24

1 Answers1

0

You try to add the Photo model to the Photo model you're querying, so either try:

$galleryphotos = $this->Gallery->find('first', array(
    'contain' => array('Photo'),
    'conditions' => array(
        'Gallery.slug'=> $slug,
        'Photo.active'=>'yes')));  

Or

$galleryphotos = $this->Gallery->Photo->find('all', array(
    'contain' => array('Gallery'),
    'conditions' => array(
        'Gallery.slug'=> $slug,
        'Photo.active'=>'yes')));

Assuming the assocation is Gallery hasMany Photo.

And this should be inside of a model, not a controller, so that you can keep your controller skinny and simply call $this->Gallery->view($slug); to get the data.

floriank
  • 25,546
  • 9
  • 42
  • 66
  • thank you Burzum, I've used your second suggestion, which does output the correct array results when I use debug($galleryphotos); However, when I use the variable $galleryphotos in the view I get the error: Notice (8): Undefined variable: galleryphotos. I haven't moved this into the model yet, as I wanted to get it working in the controller. But I will. I've looked over what I've done and can't see why I'm getting this error. What am I missing? – Paul Feb 07 '14 at 15:48