コード例 #1
0
ファイル: VoteTableSeeder.php プロジェクト: yueguchi/vote_api
 public function run()
 {
     // FKの無効化
     DB::statement('SET FOREIGN_KEY_CHECKS=0;');
     DB::table('votes')->truncate();
     $faker = Faker::create('en_US');
     for ($i = 0; $i < 100; $i++) {
         Vote::create(['title' => $faker->sentence(), 'body' => $faker->paragraph(), 'is_published' => rand(0, 1), 'created_at' => Carbon::today()]);
     }
     // FKを元に戻す
     DB::statement('SET FOREIGN_KEY_CHECKS=1;');
 }
コード例 #2
0
 public function postVote()
 {
     $categories = Input::get('categories');
     //複数文字列がカンマ区切りで渡ってくる
     $title = Input::get('title');
     $body = Input::get('body');
     $chc1 = Input::get('chc1');
     $chc2 = Input::get('chc2');
     $chc3 = Input::get('chc3', "");
     $chc4 = Input::get('chc4', "");
     $chc5 = Input::get('chc5', "");
     $other = Input::get('other', 0);
     $userId = User::select("id")->where("token", "=", Input::get("token"))->first()['id'];
     if (!($categories && $title && $body && $chc1 && $chc2 && $userId)) {
         return \Response::json(["status" => 400, "message" => "パラメータエラー"], 400);
     }
     // 「1,2,3」 と 「PHP,java」のような形で返却される文字列。
     // FIXME 大文字と小文字が区別されない。「aaa」と「AAA」が引っかかる。BINARY検索を行えば良いが、querybuilderでどう書けば良いのかが不明。。
     $categoryIdName = DB::table('categories')->select(DB::raw('group_concat(id) as id'), DB::raw('group_concat(name) as name'))->whereIn('name', explode(",", $categories))->first();
     //DB::select("select group_concat(id) as id, group_concat(name) as name from categories where name in (binary?) limit 1", explode(",", $categories));
     $insertCateIds = $categoryIdName->id;
     // 1,2,3...
     $insertCateNames = $categoryIdName->name;
     // PHP,java...
     // カテゴリテーブルにない新規はCategoriesにinsert
     $insertCateNames = str_replace(explode(",", $insertCateNames), ",", $categories);
     // cate表にinsertするnameのみを,区切りで抽出
     foreach (explode(",", $insertCateNames) as $key => $value) {
         if (!$value) {
             continue;
         }
         $id = DB::table('categories')->insertGetId(['name' => $value, 'created_at' => Carbon::now()]);
         $insertCateIds = $insertCateIds ? $insertCateIds . "," . $id : $id;
     }
     // 結果的にすべてのCategoryIdをvotesにinsertする -> 「1,4,5」のような文字列を突っ込む
     $vote = null;
     DB::transaction(function () use($title, $body, $userId, $insertCateIds, $chc1, $chc2, $chc3, $chc4, $chc5, $other, $vote) {
         $vote = Vote::create(['title' => $title, 'body' => $body, 'is_published' => 1, 'created_at' => Carbon::today(), 'user_id' => $userId, 'category_id' => $insertCateIds]);
         Choice::create(['chc1' => $chc1, 'chc2' => $chc2, 'chc3' => $chc3, 'chc4' => $chc4, 'chc5' => $chc5, "vote_id" => $vote['id'], 'created_at' => Carbon::today(), 'isDispOther' => $other]);
     });
     $ret = [];
     if ($vote) {
         $ret = ["id" => $vote['id']];
     } else {
         $ret = ["error" => "failed post vote!"];
     }
     return \Response::json($ret);
 }