當前位置: 首頁>>代碼示例>>PHP>>正文


PHP DB::transaction方法代碼示例

本文整理匯總了PHP中DB::transaction方法的典型用法代碼示例。如果您正苦於以下問題:PHP DB::transaction方法的具體用法?PHP DB::transaction怎麽用?PHP DB::transaction使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在DB的用法示例。


在下文中一共展示了DB::transaction方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。

示例1: up

 /**
  * Run the migrations.
  */
 public function up()
 {
     Schema::create('character_set_structure', function (Blueprint $table) {
         $table->increments('id');
         $table->unsignedInteger('character_set_id')->index();
         $table->unsignedInteger('version_number_id')->index();
         $table->string('description');
         $table->string('mysql_character_set');
         // Composite keys
         $table->unique(['character_set_id', 'version_number_id'], uniqid());
         // Foreign keys
         $table->foreign('character_set_id')->references('id')->on('character_set');
         $table->foreign('version_number_id')->references('id')->on('version_number');
     });
     DB::transaction(function () {
         CharacterSetStructure::unguard();
         foreach ($this->data as $datum) {
             $character_set = CharacterSet::where(['value' => $datum['character_set']])->firstOrFail();
             $version_number = VersionNumber::where(['value' => $datum['version_number']])->firstOrFail();
             $character_set_structure = new CharacterSetStructure();
             $character_set_structure->description = $datum['description'];
             $character_set_structure->mysql_character_set = $datum['mysql_character_set'];
             $character_set_structure->characterSet()->associate($character_set);
             $character_set_structure->versionNumber()->associate($version_number);
             $character_set_structure->save();
         }
         CharacterSetStructure::reguard();
     });
 }
開發者ID:fisharebest,項目名稱:webtrees-core,代碼行數:32,代碼來源:2015_12_31_006000_create_character_set_structure_table.php

示例2: store

 /**
  * Store a newly created resource in storage.
  * POST /users
  *
  * @return Response
  */
 public function store()
 {
     Input::merge(array_map('trim', Input::all()));
     $input = Input::all();
     $validation = Validator::make($input, User::$rules);
     if ($validation->passes()) {
         DB::transaction(function () {
             $user = new User();
             $user->first_name = strtoupper(Input::get('first_name'));
             $user->middle_initial = strtoupper(Input::get('middle_initial'));
             $user->last_name = strtoupper(Input::get('last_name'));
             $user->dept_id = Input::get('department');
             $user->confirmed = 1;
             $user->active = 1;
             $user->email = Input::get('email');
             $user->username = Input::get('username');
             $user->password = Input::get('password');
             $user->password_confirmation = Input::get('password_confirmation');
             $user->confirmation_code = md5(uniqid(mt_rand(), true));
             $user->image = "default.png";
             $user->save();
             $role = Role::find(Input::get('name'));
             $user->roles()->attach($role->id);
         });
         return Redirect::route('user.index')->with('class', 'success')->with('message', 'Record successfully added.');
     } else {
         return Redirect::route('user.create')->withInput(Input::except(array('password', 'password_confirmation')))->withErrors($validation)->with('class', 'error')->with('message', 'There were validation errors.');
     }
 }
開發者ID:jcyanga28,項目名稱:project-reference,代碼行數:35,代碼來源:UsersController.php

示例3: handle

 /**
  * Execute the job.
  *
  * @return void
  */
 public function handle()
 {
     if ($this->beforeTransaction()) {
         \DB::transaction($this->transaction());
         $this->afterTransaction();
     }
 }
開發者ID:whplay,項目名稱:ohmate-shop,代碼行數:12,代碼來源:BeansTransaction.php

示例4: run

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     Model::unguard();
     DB::transaction(function () {
         DB::statement('SET foreign_key_checks = 0;');
         DB::table('roles')->truncate();
         DB::table('users')->truncate();
         DB::table('folders')->truncate();
         DB::table('q_and_a')->truncate();
         DB::table('tags')->truncate();
         DB::table('comment')->truncate();
         DB::table('votes')->truncate();
         DB::table('roles')->truncate();
         DB::statement('SET foreign_key_checks = 1;');
         $this->call(RolesTableSeeder::class);
         $this->call(UsersSeeder::class);
         $this->call(FoldersSeeder::class);
         $this->call(QuestionsSeeder::class);
         $this->call(TagsSeeder::class);
         $this->call(AnswersSeeder::class);
         $this->call(VotesSeeder::class);
         $this->call(CommentForAnswerSeeder::class);
         $this->call(CommentForQuestionSeeder::class);
     });
     Model::reguard();
 }
開發者ID:a1ex7,項目名稱:asciit,代碼行數:31,代碼來源:DatabaseSeeder.php

示例5: nuevaCorreccionObservacion

 public function nuevaCorreccionObservacion($inputs)
 {
     $Correspondencia = Correspondencia::find($inputs['IdCorrespondencia']);
     if ($Correspondencia->getIdCaracter() == 1) {
         DB::transaction(function () use($inputs) {
             $oficio = new OficioSaliente();
             $oficioU = Observaciones::find($inputs['IdObservaciones']);
             $oficioU->Oficio_Saliente_Id = $inputs['IdConsecutivo'];
             $oficioU->Observacion_Usuario_Id = $oficio->getIdRevisor($inputs['IdConsecutivo'], 1);
             //Usuario que va a corregir
             $oficioU->DescripcionObservaciones = $inputs['Observacion'];
             $oficioU->save();
         });
     } else {
         DB::transaction(function () use($inputs) {
             $oficio = new OficioSaliente();
             $oficioU = Observaciones::find($inputs['IdObservaciones']);
             $oficioU->Oficio_Saliente_Id = $inputs['IdConsecutivo'];
             $oficioU->Observacion_Usuario_Id = $oficio->getIdRevisor($inputs['IdConsecutivo'], $Correspondencia->getIdCaracter());
             //Usuario que va a corregir
             $oficioU->DescripcionObservaciones = $inputs['Observacion'];
             $oficioU->save();
         });
     }
     /*DB::transaction(function () use ($inputs, $path){
     			$oficioU = Correspondencia::find($inputs['IdCorrespondencia']);
     			$oficioU->URLPDF = $path;
     			$oficioU->save();
     		});*/
     DB::transaction(function () use($inputs) {
         $oficioU = Correspondencia::find($inputs['IdCorrespondencia']);
         $oficioU->Estatus_Id = 401;
         $oficioU->save();
     });
 }
開發者ID:jonatanian,項目名稱:TT,代碼行數:35,代碼來源:Observaciones.php

示例6: approveApplication

 public function approveApplication(Request $request)
 {
     $shop_card_application_id = $request->input('require_id');
     $application = ShopCardApplication::find($shop_card_application_id);
     $customer = Customer::find($application->customer_id);
     $card_type = $application->cardType;
     try {
         \DB::transaction(function () use($application, $customer, $card_type) {
             $customer_rows = \DB::table('customers')->where('id', $customer->id);
             $customer_rows->lockForUpdate();
             $customer_row = $customer_rows->first();
             if ($customer_row->beans_total < $card_type->beans_value * $application->amount) {
                 throw new NotEnoughBeansException();
             }
             $cards = \DB::table('shop_cards')->where('card_type_id', '=', $card_type->id)->whereNull('customer_id')->limit($application->amount);
             $cards->lockForUpdate();
             if ($cards->count() < $application->amount) {
                 throw new CardNotEnoughException();
             }
             $customer->minusBeansByHand($application->amount * $card_type->beans_value);
             $cards->update(['customer_id' => $customer->id, 'bought_at' => Carbon::now()]);
             $application->update(['authorized' => true]);
             return true;
         });
     } catch (CardNotEnoughException $e) {
         return '相應卡片不足,無法繼續。';
     } catch (NotEnoughBeansException $e) {
         return '用戶邁豆不足!';
     }
     return "操作成功!";
 }
開發者ID:whplay,項目名稱:ohmate-shop,代碼行數:31,代碼來源:CardApplicationController.php

示例7: handle

 public function handle(CreateBehaviorDO $do)
 {
     \DB::transaction(function () use($do) {
         $entity = new Model();
         $entity->attributeSet()->associate($this->loadAttributeSetById($do->attribute_set_id));
         $entity->representation()->associate($this->loadRepresentationEntity($do->representation_id));
         $entity->name = $do->name;
         $entity->label = $do->label;
         $entity->default_value = $do->default_value;
         $entity->max_values_count = $do->max_values_count;
         $entity->required_create = $do->required_create;
         $entity->required_order = $do->required_order;
         $entity->save();
         if (count($do->options)) {
             foreach ($do->options as $optionDO) {
                 $optionEntity = $this->optionEntity($optionDO);
                 $entity->options()->save($optionEntity);
                 foreach ($optionDO->values as $valueDO) {
                     $valueEntity = $this->valueEntity(AttributeOptionModel::OBJECT_TYPE, $valueDO);
                     $optionEntity->values()->save($valueEntity);
                 }
             }
             $entity->options()->save($optionEntity);
         }
         if (count($do->values)) {
             foreach ($do->values as $valueDO) {
                 $entity->objectValues()->save($this->valueEntity(Model::OBJECT_TYPE, $valueDO));
             }
         }
     });
 }
開發者ID:plamenyankov,項目名稱:northstyle,代碼行數:31,代碼來源:CreateAttribute.php

示例8: run

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     $videoItems = array(array("Breakfast Show!", "This is the breakfast show description."), array("BBC News"), array("BBC News 24"), array("Dragons Den"), array("Mock The Week!"), array("Some Other Show"), array("Soundbooth Sessions"), array("The LA1 Show"), array("The One Show"), array("Star Wars"), array("Sugar TV!"), array("The Incredibles"), array("University Challenge"), array("Countdown"), array("8 out of 10 Cats Does Countdown"), array("Jurassic Park"), array("Jurassic Park 2"), array("Shrek"), array("Shrek 2"), array("Shrek 3"), array("Mission Impossible"));
     foreach ($videoItems as $a) {
         $mediaItemVideo = new MediaItemVideo(array("is_live_recording" => rand(0, 1) ? true : false, "time_recorded" => Carbon::now()->subHour(), "description" => rand(0, 4) === 0 ? "A description that should override the general media item one." : null, "enabled" => rand(0, 1) ? true : false));
         $mediaItem = new MediaItem(array("name" => $a[0], "description" => count($a) >= 2 ? $a[1] : null, "enabled" => rand(0, 1) ? true : false, "scheduled_publish_time" => Carbon::now()));
         DB::transaction(function () use(&$mediaItem, &$mediaItemVideo) {
             $mediaItem->save();
             $mediaItem->videoItem()->save($mediaItemVideo);
         });
         $this->addLikes($mediaItem);
         $this->addComments($mediaItem);
     }
     //$mediaItemLiveStream = new MediaItemLiveStream(array(
     //	"enabled"	=>	true
     //));
     $mediaItem = new MediaItem(array("name" => "Lunchtime Show!", "description" => "This is the lunchtime show description.", "enabled" => true, "scheduled_publish_time" => Carbon::now()));
     DB::transaction(function () use(&$mediaItem, &$mediaItemLiveStream) {
         $mediaItem->save();
         //	$mediaItem->liveStreamItem()->save($mediaItemLiveStream);
     });
     $this->addLikes($mediaItem);
     $this->addComments($mediaItem);
     $this->command->info('Media items created!');
 }
開發者ID:joshhodgson,項目名稱:Website,代碼行數:30,代碼來源:MediaItemSeeder.php

示例9: addyear

 public function addyear(Request $request)
 {
     $postData = $request->all();
     $contractId = $postData['PdContract'];
     $year = $postData['year'];
     $qltyFormulas = PdContractQtyFormula::all();
     $formulaValues = \FormulaHelpers::getDataFormulaContract($qltyFormulas, $contractId, $year);
     $resultTransaction = \DB::transaction(function () use($qltyFormulas, $formulaValues, $contractId, $year) {
         $attributes = ['CONTRACT_ID' => $contractId];
         $yAttributes = ['CONTRACT_ID' => $contractId, 'YEAR' => $year];
         $yValues = ['CONTRACT_ID' => $contractId, 'YEAR' => $year];
         // 	     	PdContractYear::where($yAttributes)->delete();
         foreach ($qltyFormulas as $key => $qltyFormula) {
             $attributes['FORMULA_ID'] = $qltyFormula->ID;
             $values = $attributes;
             $calculation = PdContractCalculation::updateOrCreate($attributes, $values);
             /* $sql = "INSERT INTO pd_contract_calculation(FORMULA_ID,CONTRACT_ID) "
             			. "VALUE(".$aryRequest['FORMULA_ID'.$id].",".$aryRequest['CONTRACT_ID'].")"; */
             $formulaValue = (int) $formulaValues[$qltyFormula->ID];
             $yAttributes['CALCULATION_ID'] = $calculation->ID;
             $yValues['CALCULATION_ID'] = $calculation->ID;
             $yValues['FORMULA_VALUE'] = $formulaValue;
             $contractYear = PdContractYear::updateOrCreate($yAttributes, $yValues);
             /* $val = (int) $aryValue[$formulaId[$key]]; // abc($id,$contractId)  se thay bang cong thuc
              		$sql2 = "INSERT INTO pd_contract_year(CALCULATION_ID,YEAR,FORMULA_VALUE,CONTRACT_ID) VALUE($id,$year,'$val',$contractId)";
              		$sql2=str_replace("''", "NULL", $sql2); */
         }
     });
     $results = $this->loadData($contractId, $postData);
     return response()->json($results);
 }
開發者ID:hunglmtb,項目名稱:eb,代碼行數:31,代碼來源:ContractCalculateController.php

示例10: run

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     DB::transaction(function () {
         // create admin user
         $root = factory(App\User::class)->create(['name' => 'Administrator', 'email' => 'admin@example.com', 'password' => bcrypt('123456'), 'username' => 'admin', 'location' => 'Da Nang', 'country' => 'Viet Nam', 'biography' => 'Dev', 'occupation' => 'Dev', 'website' => 'greenglobal.vn', 'image' => 'avatar.jpg']);
         // create default roles
         $admin = new Role();
         $admin->name = 'admin';
         $admin->display_name = 'Administrator';
         $admin->description = 'User is allowed to manage all system.';
         $admin->active = 1;
         $admin->save();
         // create default guest roles
         $guest = new Role();
         $guest->name = 'guest';
         $guest->display_name = 'Guest';
         $guest->description = 'User are not logged in.';
         $guest->active = 1;
         $guest->save();
         // attach roles
         $root->attachRole($admin);
         // create root permission
         $admin = new NodePermission();
         $admin->name = 'Root';
         $admin->display_name = 'Root permission';
         $admin->description = 'The root.';
         $admin->save();
         // create all permission to admin
         $root = new PermissionRole();
         $root->permission_id = 1;
         $root->role_id = 1;
         $root->status = 1;
         $root->save();
     });
 }
開發者ID:autn,項目名稱:gcl-users,代碼行數:40,代碼來源:UserModuleSeeder.php

示例11: postUpdate

 public function postUpdate($id)
 {
     $rules = array('txtNombres' => 'required|min:2|max:100', 'txtApellidos' => 'required|min:2|max:100', 'txtEmail' => 'required|min:2|max:100', 'username' => 'required|min:2|max:100', 'txtPassword' => 'required|min:2|max:100', 'txtRol' => 'required|max:100', 'txtEstado' => 'required|max:100');
     $messages = array('required' => 'El campo :attribute es obligatorio.', 'min' => 'El campo :attribute no puede tener menos de :min carácteres.', 'email' => 'El campo :attribute debe ser un email válido.', 'max' => 'El campo :attribute no puede tener más de :min carácteres.', 'unique' => 'El :attribute ingresado ya existe en la base de datos', "numeric" => "El campo :attribute debe ser un numero");
     $friendly_names = array("txtNombres" => "Nombres", "txtApellidos" => "Apellidos", "txtEmail" => "Email", "username" => "Usuario", "txtPassword" => "Password", "txtRol" => "Rol", "txtEstado" => "Estado");
     $validation = Validator::make(Input::all(), $rules, $messages);
     $validation->setAttributeNames($friendly_names);
     if ($validation->fails()) {
         return Redirect::to('usuarios/modificar/' . $id)->withErrors($validation)->withInput();
     } else {
         try {
             DB::transaction(function () use($id) {
                 $usuario = Usuario::find($id);
                 $usuario->username = strtoupper(Input::get("username"));
                 $usuario->nombres = strtoupper(Input::get("txtNombres"));
                 $usuario->apellidos = strtoupper(Input::get("txtApellidos"));
                 $usuario->email = strtoupper(Input::get("txtEmail"));
                 $usuario->password = strtoupper(Hash::make(Input::get("txtPassword")));
                 $usuario->roles_id = Input::get("txtRol");
                 $usuario->estado = Input::get("txtEstado");
                 $usuario->save();
             });
         } catch (ValidationException $ex) {
             //return "1";
             return Redirect::to("usuarios")->with("modificar", true);
         } catch (Exception $ex) {
             //return "2";
             return Redirect::to("usuarios")->with("modificar", true);
         }
         return Redirect::to("admin")->with("modificar", true);
     }
 }
開發者ID:omarmurcia,項目名稱:AHJNProject,代碼行數:32,代碼來源:UsuariosController.php

示例12: getExercise

 public function getExercise()
 {
     $json_data = file_get_contents(public_path() . "/js/ejercicio4.json");
     $json = json_decode($json_data);
     DB::transaction(function () use(&$json) {
         $results = DB::select("insert into Exercises (id, description) SELECT COALESCE(MAX(id),0) + 1, 'Interfaz de Constantes' FROM exercises RETURNING id ");
         $exercise_id = $results[0]->id;
         echo $exercise_id;
         $step_number = 0;
         foreach ($json->excercises as $step) {
             $step_number++;
             $results = DB::select("insert into explanations(id, description,exercise_id,step_number,incremental_example,progress) SELECT COALESCE(MAX(id),0) + 1, ?,?,?,?,? FROM explanations RETURNING id ", array($step->explanation, $exercise_id, $step_number, implode("\n", $step->incrementalText), $step->progress));
             $explanation_id = $results[0]->id;
             foreach ($step->answers as $answer) {
                 if (isset($answer->error)) {
                     $error = $answer->error;
                 } else {
                     $error = "";
                 }
                 $description = implode("\n", $answer->text);
                 $correct = $answer->rightAnswer ? 1 : 0;
                 $results = DB::select("insert into answers (id, description,exercise_id,error,correct,step_number) SELECT COALESCE(MAX(id),0) + 1, ?,?,?,?,? FROM answers RETURNING id ", array($description, $exercise_id, $error, $correct, $step_number));
             }
         }
     });
     echo var_dump(DB::getQueryLog());
 }
開發者ID:hugosama1,項目名稱:ile,代碼行數:27,代碼來源:ExerciseController.php

示例13: requestRefund

 public function requestRefund()
 {
     $order_id = Input::get('order_id');
     $order = AgencyOrder::find($order_id);
     if (!isset($order)) {
         return Response::json(array('errCode' => 21, 'message' => '該訂單不存在'));
     }
     $refund_record = RefundRecord::where('order_id', '=', $order_id)->get();
     if (count($refund_record) != 0) {
         return Response::json(array('errCode' => 22, 'message' => '申請已提交'));
     }
     if ($order->trade_status != 1 || $order->process_status != 1) {
         return Response::json(array('errCode' => 23, 'message' => '該訂單不可申請退款'));
     }
     try {
         DB::transaction(function () use($order) {
             $order->trade_status = 2;
             $order->save();
             $refund_record = new RefundRecord();
             $refund_record->order_id = $order->order_id;
             $refund_record->user_id = Sentry::getUser()->user_id;
             $refund_record->save();
         });
     } catch (Exception $e) {
         return Response::json(array('errCode' => 24, 'message' => '退款申請失敗,請重新申請'));
     }
     return Response::json(array('errCode' => 0, 'message' => '申請成功'));
 }
開發者ID:Jv-Juven,項目名稱:carService,代碼行數:28,代碼來源:OrderController.php

示例14: dUserNotice

 public function dUserNotice()
 {
     if (!Sentry::check()) {
         return Response::json(array('errCode' => 10, 'message' => '請登錄'));
     }
     $user = Sentry::getUser();
     $join_coms = ArticleJoinCom::where('receiver_id', '=', $user->id)->where('is_delete', '=', 0)->get();
     $replys = ArticleJoinReply::where('receiver_id', '=', $user->id)->where('is_delete', '=', 0)->get();
     try {
         DB::transaction(function () use($replys, $join_coms) {
             if (count($join_coms) != 0) {
                 foreach ($join_coms as $com) {
                     $com->is_delete = 1;
                     $com->save();
                 }
             }
             if (count($replys) != 0) {
                 foreach ($replys as $reply) {
                     $reply->is_delete = 1;
                     $reply->save();
                 }
             }
         });
     } catch (\Exception $e) {
         return Response::json(array('errCode' => 11, 'message' => '操作失敗'));
     }
     return Response::json(array('errCode' => 0, 'message' => '刪除成功'));
 }
開發者ID:Jv-Juven,項目名稱:gift,代碼行數:28,代碼來源:NoticeController.php

示例15: genBLMR

 public function genBLMR(Request $request)
 {
     $postData = $request->all();
     $pid = $postData['id'];
     $shipCargoBlmr = $this->getShipCargoBlmr($pid);
     $xid = $shipCargoBlmr ? $shipCargoBlmr->ID : 0;
     $results = \DB::transaction(function () use($xid, $pid) {
         $mdl = $this->modelName;
         $transportType = $mdl::getTableName();
         $shipCargoBlmr = ShipCargoBlmr::getTableName();
         if ($xid > 0) {
             // 			    			\DB::enableQueryLog();
             $values = $this->getUpdateFields($shipCargoBlmr, $transportType);
             ShipCargoBlmr::join($transportType, "{$transportType}.ID", '=', "{$shipCargoBlmr}.PARENT_ID")->where("{$shipCargoBlmr}.ID", $xid)->update($values);
             // 			   \Log::info(\DB::getQueryLog());
             return 'Success(only update exist rows)';
         } else {
             $pdVoyage = PdVoyage::getTableName();
             $storage = Storage::getTableName();
             $values = $this->getInsertFields($pid, $pdVoyage, $storage, $transportType);
             $mdl::join($pdVoyage, "{$pdVoyage}.ID", '=', "{$transportType}.VOYAGE_ID")->join($storage, "{$storage}.ID", '=', "{$pdVoyage}.STORAGE_ID")->where("{$transportType}.ID", $pid)->select($values)->chunk(10, function ($rows) {
                 ShipCargoBlmr::insert($rows->toArray());
             });
             return 'Success!';
         }
     });
     return response()->json($results);
 }
開發者ID:hunglmtb,項目名稱:eb,代碼行數:28,代碼來源:VoyageController.php


注:本文中的DB::transaction方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。