Skip to content

Instantly share code, notes, and snippets.

@Xymanek
Created June 20, 2016 15:05
Show Gist options
  • Save Xymanek/bc673db78d9bbc1d13edb278ac37eaa0 to your computer and use it in GitHub Desktop.
Save Xymanek/bc673db78d9bbc1d13edb278ac37eaa0 to your computer and use it in GitHub Desktop.
<?php
// \App\Model\Table\PollAnswersTable
public function countVotes ($id)
{
/** @var \App\Model\Entity\Poll $poll */
$poll = $this->get($id, ['contain' => 'PollAnswers']);
// Some logic here, it's irrerevant
// Calculate the score
foreach ($poll->poll_answers as $answer) {
$score = $poll->users_count === 0 ? 0 : $answer->votes_count / $poll->users_count;
if ($answer->score !== $score) {
$answer->score = $score; // <---------------------- This isn't saved
$poll->dirty('answers', true);
}
}
// Save the poll
if (!$this->save($poll)) {
throw new InternalErrorException(__('Failed to update the votes counter'));
}
}
<?php
class PollsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize (array $config)
{
$this->table('polls');
$this->displayField('title');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('PollAnswers', [
'foreignKey' => 'poll_id'
]);
}
}
class PollAnswersTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize (array $config)
{
$this->table('poll_answers');
$this->displayField('title');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Polls', [
'foreignKey' => 'poll_id',
'joinType' => 'INNER'
]);
$this->hasMany('PollVotes', [
'foreignKey' => 'answer_id'
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment