I have an array that I am passing to my view and it’s joined with multiple tables. Let’s call this array Submissions. All submissions contain SubmissionVotes and a typical data submission object looks like this:
[1] => Array
(
[Submission] => Array
(
[user_id] => 17
[title] => Yo mama so fat when she went to the movies she sat next to everyone
[source] => http://www.ahajokes.com/ym01.html
[slug] => yo-mama-so-fat-when-she-went-to-the-movies-she-sat-next
[category] => funny
[created] => 2012-09-26 21:00:35
[id] => 104
)
[User] => Array
(
[id] => 17
[username] => bob_cobb
)
[SubmissionsVote] => Array
(
[0] => Array
(
[id] => 323
[user_id] => 2
[submission_id] => 104
[vote_type] => up
[when] => 0000-00-00 00:00:00
[voted_ip] => 842844107
)
[1] => Array
(
[id] => 322
[user_id] => 17
[submission_id] => 104
[vote_type] => up
[when] => 0000-00-00 00:00:00
[voted_ip] => 1163843117
)
)
[SubmissionThumbnails] => Array
(
[0] => Array
(
[id] => 6
[submission_id] => 104
[original] => http://www.ahajokes.com/g/smlogo.gif
[extension] => jpg
[slug] => http://www.ahajokes.com/g/smlogo.gif
)
)
)
Right now I’m just doing a foreach through this in my view and grabbing: $submission['Submission']['id'], $submission['Submission']['category'] and other useful stuff from it. This is all fine, but I’d like to somehow be able to just make a new object (or something equally as intuitive) that has the number of up vote_type and number of down vote_type so that I can just be like $submission['Submission']['upVotes'] / $submission['Submission']['downVotes'].
I’m doing the join in CakePHP and here is my query:
$this->find('all', array(
'fields' => array(
'Submission.user_id',
'Submission.title',
'Submission.source',
'Submission.slug',
'Submission.category',
'Submission.created',
'User.id',
'User.username'),
'order' => 'Submission.created DESC'));
The only reason I want to do this is because going through and having to add up all upvotes and downvotes within my view would be quite the pain, not to mention pretty sloppy.
How can I improve this?
You could try using virtual fields: http://book.cakephp.org/2.0/en/models/virtual-fields.html.
In your
Submissionmodel, you would have something similar to:In the above example,
submission_votesis your database table name for yourSubmissionVotemodel. Be sure to heed the warning: http://book.cakephp.org/2.0/en/models/virtual-fields.html#limitations-of-virtualfields.If you just want to manipulate the data array, another option might be to use the something from the
Hashclass, such asHash::reduce.http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::reduce