public function defaultVotesSet() { // check that the count of GroupVotes with this voting's id is equal to the count of all groups * number of voting items of this voting $groupCount = Group::all()->count(); $votingItemCount = VotingItem::ofVoting($this->id)->count(); $correctAmount = $groupCount * $votingItemCount; if (GroupVote::ofVoting($this->id)->count() == $correctAmount) { return true; } return false; }
/** * Saves the answers of a reading to the database * * @return mixed */ public function saveAnswers() { // Get voting id (doesn't check if a voting with that id exists because if it doesn't, vote creation will fail) $v_id = Input::get('voting'); // Get member/vote pairs $votes = Input::get('data'); // Get voting items of this voting and put their ids in another array to not make a lot of queries afterwards $votingItems = VotingItem::ofVoting($v_id)->get(); $votingItemIds = []; foreach ($votingItems as $vi) { $votingItemIds[] = $vi->id; } // Save votes to the database foreach ($votes as $vote) { // Check if a vote already exists (which means the user is changing the vote from the form) and delete it $prevVotes = Vote::where(['voting_id' => $v_id, 'member_id' => $vote['member_id']])->get(); if ($prevVotes->count() > 0) { foreach ($prevVotes as $v) { $v->delete(); // Delete vote for every voting item } } // Create the new vote foreach ($votingItemIds as $vItem_id) { // Make string which is the key to this voting item's answer in the $vote[] array $str = 'answer_for_' . $vItem_id; // If the key exists in the $vote[] array, save the vote to the database if (isset($vote[$str]) || array_key_exists($str, $vote)) { if ($vote[$str] == '') { $answer = null; } else { $answer = $vote[$str]; } // Save the vote to the database Vote::create(['voting_id' => $v_id, 'voting_item_id' => $vItem_id, 'member_id' => $vote['member_id'], 'answer_id' => $answer]); } } } // Return success json return Response::json('success', 200); }