/** * vote a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function postChoice(Request $request) { $id = $request->input('id'); $chcNo = $request->input('chcNo'); $aggregate = Aggregate::where("vote_id", "=", $id)->get(); // ユーザーが投票した選択肢のカラムを抽出する $chcColumnName = Aggregate::getChcColumnName($chcNo); // 得点の設定 $chcNoPoint = 0; if (isset($aggregate[0])) { $chcNoPoint = $aggregate[0]->{$chcColumnName} ?? 0; } // 存在する場合はupdate。初はinsert $message = ""; if (isset($aggregate[0])) { $aggregate[0]->{$chcColumnName} = $chcNoPoint + 1; $aggregate[0]->save(); $message = "update success."; } else { $insertChcColumnName = ""; if ($chcColumnName === "other") { $insertChcColumnName = $chcColumnName; } else { $insertChcColumnName = 'chc' . $chcNo; } $id = DB::table('aggregates')->insertGetId(['vote_id' => $id, $insertChcColumnName => $chcNoPoint + 1, 'created_at' => Carbon::now()]); $message = "insert success."; } return \Response::json(["id" => $id, "message" => $message]); }
/** * Voteとそれに紐づく情報をまとめて取得する * コメント情報は膨大になる、かつ可変であるため別APIで取得する */ public function getDisplayVoteInfo($id) { $dispVoteInfo = DB::table('votes as v')->select('v.id', 'v.title', 'v.body', 'c.chc1', 'c.chc2', 'c.chc3', 'c.chc4', 'c.chc5', 'c.isDispOther')->leftJoin('choices as c', 'v.id', '=', 'c.vote_id')->where('v.id', '=', $id)->first(); // ガテゴリ情報の取得 1,2,3..って形でvotesからカテゴリIDを取得し、カテゴリ名をcatgoriesテーブルから取得する $whereIds = DB::table('votes')->select(DB::raw('group_concat(category_id) as category_id'))->where('id', '=', $id)->first()->category_id; $dispVoteInfo->categories = DB::table('categories')->select('id', 'name')->whereIn('id', explode(',', $whereIds))->get(); // 集計情報の取得 $dispVoteInfo->aggregates = Aggregate::where("vote_id", "=", $id)->first(); return \Response::json($dispVoteInfo); }
/** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { // parent::boot($router); // route.phpでパラメータに指定した{parameter}を第一引数に指定する $router->model('vote_id', 'App\\Model\\Vote', function () { }); $router->bind('choices_vote_id', function ($vote_id) { return \App\Model\Choice::where("vote_id", "=", $vote_id)->first(); }, function () { }); $router->bind('aggregate_vote_id', function ($vote_id) { return \App\Model\Aggregate::where("vote_id", "=", $vote_id)->first(); }, function () { }); }