checcco
checcco

Reputation: 35

CakePHP - Sorting a model's records by a serialized array of ids stored in another model to which the first array belongs to

I've an hasMany asscociation set up so that an Account has many Sections. The final user can create sections and then sort them. I store the order of the Sections in a serialized array. This is what I get when I read an Account:

Array
(
    [Account] => Array
        (
            [id] => 252446224806973
            [order] => Array
                (
                    [0] => 481
                    [1] => 480
                    [2] => 482
                )

            [bgcolor] => #FFF
        )

    [Section] => Array
        (
            [0] => Array
                (
                    [id] => 480
                    [content] => Array
                        (
                            [body] => <p>Test</p>
                            [bgcolor] => 
                            [color] => #000
                        )

                    [kind] => text
                    [marginbottom] => 0
                    [account_id] => 252446224806973
                )

            [1] => Array
                (
                    [id] => 481
                    [content] => Array
                        (
                            [colorscheme] => light
                            [num_posts] => 2
                        )

                    [kind] => comment
                    [marginbottom] => 0
                    [account_id] => 252446224806973
                )

            [2] => Array
                (
                    [id] => 482
                    [content] => Array
                        (
                            [body] => 
                        )

                    [kind] => sound
                    [marginbottom] => 0
                    [account_id] => 252446224806973
                )

        )

)

As you can see Sections are returned ordered by their id. I'd like them to be returned ordered by the order array in the Account model (that has already been unserialized in the afterFind). I don't think I can set up this in the association itself. But I guess there must be a method in the Set library to apply in the afterFind. I can surely write some code to do this, but I'd prefer a cake way.

Q: Can't you create an order field in the Sections table?

A: No, I simply can't :)

Upvotes: 1

Views: 327

Answers (1)

Related Questions