views:

25

answers:

1

I have two models in cakephp, Link and Vote.

I want to have the sum of the votes for every link in my Link model. Here is a print of my findAll function :

[1] => Array
    (
        [Link] => Array
            (
                [id] => 1
                [url] => http://www.google.com
                [date_added] => 2010-08-19 11:36:56
                [valid] => 1
            )

        [Vote] => Array
            (
                [0] => Array
                    (
                        [link_id] => 1
                        [user_id] => 0
                        [vote] => 3
                    )

                [1] => Array
                    (
                        [link_id] => 1
                        [user_id] => 4
                        [vote] => 4
                    )

            )

    )

What I would like to have is this (note the votes attribute) :

[1] => Array
    (
        [Link] => Array
            (
                [id] => 1
                [url] => http://www.google.com
                [date_added] => 2010-08-19 11:36:56
                [valid] => 1
                [votes] => 7
            )

        [Vote] => Array
            (
                [0] => Array
                    (
                        [link_id] => 1
                        [user_id] => 0
                        [vote] => 3
                    )

                [1] => Array
                    (
                        [link_id] => 1
                        [user_id] => 4
                        [vote] => 4
                    )

            )

    )

But I have no idea where I'm supposed to do the SUM of the votes.

A: 

You can create a virtual field "votes" in your Link model. http://book.cakephp.org/view/1608/Virtual-fields

var $virtualFields = array(    
    'votes' => 'COUNT ...'
);
Rafael Vega
Yep, I tried to use a virtual field in my Link model but I couldn't get it to work without a full SQL query.
kevin
And what's the problem with that?
Rafael Vega
It feels a bit 'dirty', I was hoping I could sum them without the use of SQL, I wanted to abstract this operation so that it isn't dependent of a database management system.
kevin
Writing SQL shouldn't feel "dirty" just because your framework helps you write most of it. Now, You could implement a behavior that adds a virtual field for your has_many models and the SQL it creates depends on the database engine you chose in your app/config.php. Seems like overkill to me but you might need something like that.
Rafael Vega