Tuesday, July 3, 2012

Paginating an associated model

Hey everyone,

I have a page in my application where I show information about 1 category and all of it's products (category hasMany product, product belongsTo category). I have been using a call to $this->Category->find() supplying it with conditions and containments to get something like that following:
Array
(
    [0] => Array
        (
            [Category] => Array
                (
                    [id] => 1
                    [name] => Shoes
                )
            [Product] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [name] => New Balance M1
                        )
                    [1] => Array
                        (
...
                        )
                )
        )
)

And now I need to paginate the products. I tried calling $this->paginate(), passing in 'Product' with conditions and such but then I either need to make yet another find() call to get the category information or to have the category information duplicated across the entire array like that:
Array
(
    [0] => Array
        (
            [Product] => Array
                (
                    [id] => 1
                    [name] => New Balance M1
                )
            [Category] => Array
                (
                    [id] => 1
                    [name] => Shoes
                )
        )
    [1] => Array
        (
            [Product] => Array
                (
                    [id] => 2
                    [name] => UG Ascot Slipper
                )
            [Category] => Array
                (
                    [id] => 1
                    [name] => Shoes
                )
        )
    [2] => Array
        (
...
        )
)

As you can see, I don't want the same category information to be duplicated across the entire array, and I want to avoid having to use two queries (one paginate() for my products and one find() for my category). Is there a way to paginate my products and get the information of that 1 category associated with them, similar to the format of the first array in just 1 neat call?

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: