Sunday, March 4, 2012

How to get all products with one PhotoSmall and at least one PhotoBig

Hi, I have a product.

The product can have one 'small' photo, and several 'big' photos

The product is associated to photo using one table, aliases and conditions.

I need a query to find all product with one 'small' photo and *at least* one 'big' photo

I've tried the following code without success

    $this->Product->recursive = -1;
    $conditions = array('Product.category_id'=> $cats);
    $joins = array(
        array('table' => 'photos',
            'alias' => 'PhotoBig',
            'type' => 'INNER',
            'conditions' => array(
                'Product.id = PhotoBig.product_id',
            )
        ),
        array('table' => 'photos',
            'alias' => 'PhotoSmall',
            'type' => 'INNER',
            'conditions' => array(
                'Product.id = PhotoSmall.product_id',
            )
        )
    );
    $this->paginate = array(
        'limit' => 12,
        'conditions' => $conditions,
        'joins' => $joins,
    );


    // app/models/product.php
    <?php
    class Product extends AppModel {
   var $name = 'Product';
   //The Associations below have been created with all possible keys, those that are not needed can be removed
   var $hasOne = array(
       'PhotoSmall' => array(
           'className' => 'Photo',
   'foreignKey' => 'product_id',
   'dependent' => true,
   'conditions' => 'PhotoSmall.tipo = "small"',
       ));
        var $hasMany = array(
   'PhotoBig' => array(
   'className' => 'Photo',
   'foreignKey' => 'product_id',
   'dependent' => true,
   'conditions' => 'PhotoBig.tipo = "big"',
   'order' => 'PhotoBig.order',
   ));
    }


    <?php
    // app/models/photo.php
    class Photo extends AppModel {
        var $name = 'Photo';
        var $actsAs = array(
            'FileUpload.FileUpload' => array(
                'uploadDir' => 'files/products',
            ),
        );
        var $belongsTo = array('Product');
        
        
        function beforeSave($options = array()) {
            if(!empty($this->data)) {
                if($this->alias == 'PhotoBig') {
                    $this->data[$this->alias]['type'] = 'big';
                }
                else {
                    $this->data[$this->alias]['type'] = 'small';
                }
            }
            return true;
        }
    }


If there's a better schema (or way) to do this I'll be glad to hear you.

Thanks

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
 
 
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: