本文整理汇总了PHP中Quote::save方法的典型用法代码示例。如果您正苦于以下问题:PHP Quote::save方法的具体用法?PHP Quote::save怎么用?PHP Quote::save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Quote
的用法示例。
在下文中一共展示了Quote::save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: save
public function save()
{
# Set validation rules
$rules = ['firstname' => 'required', 'lastname' => 'required', 'email' => 'required', 'phone' => 'required', 'location' => 'required', 'service_category' => 'required', 'service_detail' => 'required'];
$validator = Validator::make(Input::all(), $rules);
# Handle invalid data
if ($validator->fails()) {
return View::make('error')->with('message', 'Looks like there\'s some missing data');
}
$quote = new Quote();
$quote->firstname = Input::get('firstname');
$quote->lastname = Input::get('lastname');
$quote->email = Input::get('email');
$quote->phone = Input::get('phone');
$quote->location = Input::get('location');
$quote->service_category = Input::get('service_category');
$quote->service_detail = Input::get('service_detail');
$quote->save();
$email = Input::get('email');
# Shoot email to marketing team
Mail::send('emails.marketing', Input::all(), function ($message) use($email) {
$message->to('marketing@chenenetworks.com')->subject($email . ' is requesting a quote');
});
return View::make('thank_you')->with(['person' => 'experienced personnel']);
}
示例2: run
public function run()
{
$form = new AddQuoteForm();
if (!empty($_POST['AddQuoteForm']) && is_array($_POST['AddQuoteForm'])) {
$form->attributes = $_POST['AddQuoteForm'];
if ($form->validate()) {
$quote = new Quote();
$quote->textEn = $form->textEn;
$quote->textRu = $form->textRu;
$quote->authorId = 0;
$quote->notes = $form->author . ' : ' . $form->notes;
if ($quote->save()) {
/*
* Send emaiil with notification to admin.
*/
$email = Yii::app()->email;
$email->type = 'text/plain';
$email->to = Yii::app()->params['adminEmail'];
$email->subject = 'New quote request.';
$email->message = $this->controller->renderPartial('_emailAdd', array('quote' => $quote), true);
$email->send();
$this->controller->redirect(array('addThanks'));
}
}
}
$this->controller->render('add', array('form' => $form));
}
示例3: add
public function add()
{
$quote = new Quote();
$quote->user_id = $this->session->userdata('id');
$quote->text = $this->input->post('body');
$quote->author = $this->input->post('author');
$quote->save();
header('Location: /quotes');
}
示例4: run
public function run($context)
{
$preferences = $context->preferences;
$quote_count = 0;
$stocks = $context->stocks;
foreach ($stocks as $stock) {
if (!$stock->attivo) {
continue;
}
if ($stock->mercato != 'eurotlx' && $stock->mercato != 'tlx') {
continue;
}
$quote = new Quote();
$quote->isin = $stock->isin;
$quote->quotazione = isin2value_tlx($quote->isin, $preferences->isin_lookup_eurotlx);
$quote->data = date('Y-m-d');
$quote->ora = date('H:i:s');
if (is_numeric($quote->quotazione)) {
$quote->save();
$quote_count++;
}
}
printf("%s fetched %d quotes\n", get_called_class(), $quote_count);
}
示例5: actionCreate
/**
* Creates a new model.
*
* If creation is successful, the browser will be redirected to the 'view' page.
*
* @param bool $quick If true, this indicates the action is being requested via AJAX
*/
public function actionCreate($quick = false, $duplicate = false)
{
$model = new Quote();
if ($duplicate && !isset($_POST['Quote'])) {
$copiedModel = Quote::model()->findByPk($duplicate);
if (!empty($copiedModel)) {
foreach ($copiedModel->attributes as $name => $value) {
if ($name != 'id') {
$model->{$name} = $value;
}
}
$model->setLineItems($this->duplicateLineItems($copiedModel), false, true);
}
}
$users = User::getNames();
if ($quick && !Yii::app()->request->isAjaxRequest) {
throw new CHttpException(400);
}
$currency = Yii::app()->params->currency;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Quote'])) {
$model->setX2Fields($_POST['Quote']);
$model->currency = $currency;
$model->createDate = time();
$model->lastUpdated = $model->createDate;
$model->createdBy = Yii::app()->user->name;
$model->updatedBy = $model->createdBy;
if (empty($model->name)) {
$model->name = '';
}
if (isset($_POST['lineitem'])) {
$model->lineItems = $_POST['lineitem'];
}
if (!$model->hasLineItemErrors) {
if ($model->save()) {
$model->createEventRecord();
$model->createActionRecord();
$model->saveLineItems();
if (!$quick) {
$this->redirect(array('view', 'id' => $model->id));
} else {
if (isset($_GET['recordId']) && isset($_GET['recordType'])) {
$recordId = $_GET['recordId'];
$recordType = $_GET['recordType'];
$relatedModel = X2Model::model($_GET['recordType'])->findByPk($recordId);
// tie record to quote
if ($relatedModel) {
$relate = new Relationships();
$relate->firstId = $model->id;
$relate->firstType = "Quote";
$relate->secondId = $relatedModel->id;
$relate->secondType = $recordType;
$relate->save();
$model->createAssociatedAction(X2Model::getAssociationType(get_class($relatedModel)), $relatedModel->id);
}
}
return;
}
}
}
}
// get products
$products = Product::activeProducts();
$viewData = array('model' => $model, 'users' => $users, 'products' => $products, 'quick' => $quick);
if (!$quick) {
$this->render('create', $viewData);
} else {
if ($model->hasErrors() || $model->hasLineItemErrors) {
// Sneak into the response that validation failed via setting
// the response code manually:
header('HTTP/1.1 400 Validation Error');
}
$this->renderPartial('create', $viewData, false, true);
}
}
示例6: ProductBundleNote
$product_id = $product->save();
$pb->set_productbundle_product_relationship($product_id, $product_key, $product_bundle_id);
break;
}
//while
}
//foreach
$pb->tax = 0;
$pb->shipping = 0;
$pb->save();
//Save any product bundle comment
if (isset($bundle['comment'])) {
$product_bundle_note = new ProductBundleNote();
$product_bundle_note->description = $bundle['comment'];
$product_bundle_note->save();
$pb->set_product_bundle_note_relationship($bundle_key, $product_bundle_note->id, $product_bundle_id);
}
$pb->set_productbundle_quote_relationship($focus->id, $product_bundle_id, $bundle_key);
$focus->tax += $pb->tax;
$focus->shipping += $pb->shipping;
$focus->subtotal += $pb->subtotal;
$focus->deal_tot += $pb->deal_tot;
$focus->new_sub += $pb->new_sub;
$focus->total += $pb->total;
}
//foreach
//Save the quote
$focus->save();
}
//foreach
}
示例7: run
public function run()
{
if ($this->id == 'edit') {
$id = !empty($_GET['id']) ? $_GET['id'] : 0;
$quote = Quote::model()->with('tags', 'author')->findByPk($id);
if ($quote === null) {
throw new CHttpException(404, 'Quote not found');
}
} else {
// add action
$quote = new Quote();
}
if (!$quote->author) {
$quote->author = new Author();
}
if (!empty($_POST['Quote']) && is_array($_POST['Quote'])) {
$quote->attributes = $_POST['Quote'];
/*
* Process approved time.
*/
$approved = !empty($_POST['Quote']['approvedTime']);
if (!$quote->approvedTime && $approved) {
$quote->approvedTime = time();
} elseif (!$approved) {
$quote->approvedTime = 0;
}
/*
* Process author.
*/
if ($_POST['Quote']['authorId']) {
// Existing author.
$author = Author::model()->findByPk($_POST['Quote']['authorId']);
if ($author === null) {
throw new CException("Author with \"{$_POST['Quote']['authorId']}\" not found.");
}
} else {
// New author.
$authorName = $_POST['Quote']['authorCustomName'];
// At first try to find author with the same name.
$criteria = new CDbCriteria();
$criteria->condition = 'name = :name';
$criteria->params = array(':name' => $authorName);
$author = Author::model()->find($criteria);
if ($author === null) {
$author = new Author();
$author->name = $authorName;
$author->save();
}
}
$quote->authorId = $author->id;
/*
* Process tags.
*/
if (!empty($_POST['tags']) && is_array($_POST['tags'])) {
$tags = $_POST['tags'];
} else {
$tags = array();
}
$tagsObj = array();
foreach ($tags as $tag) {
$tagsObj[] = Tag::model()->findByPk($tag);
}
$quote->tags = $tagsObj;
if ($quote->save()) {
Yii::app()->user->setFlash('generalMessage', 'Quote was saved successfully.');
$this->controller->redirect(array('list'));
}
}
$criteria = new CDbCriteria();
$criteria->order = 'name';
$authors = Author::model()->findAll($criteria);
$this->controller->render('edit', array('quote' => $quote, 'authors' => $authors));
}
示例8: create_history
public function create_history($id)
{
$this->autoRender = false;
// backup old version
$quote_id = (int) $id;
App::import('Model', 'QuoteManager.Quote');
$quote = new Quote();
$quote_model = new Quote();
$quote_model->recursive = -1;
// cake_debug($quote_id); exit;
$backup_data = $quote->find('first', array('conditions' => array('Quote.id' => $quote_id)));
$update_version = $quote->find('first', array('conditions' => array('Quote.id' => $quote_id)));
$versions = $quote_model->find('all', array('conditions' => array('Quote.vid' => $quote_id)));
$current_version = count($versions) + 1;
$quote_number_split = explode('-', $update_version['Quote']['quote_number']);
$update_version['Quote']['quote_number'] = "{$quote_number_split[0]}-{$current_version}";
$this->request->data['Quote']['quote_number'] = "{$quote_number_split[0]}-{$current_version}";
$update_version['Quote']['current_version'] = $current_version;
$update_version['Quote']['status'] = "Revision";
// pr($update_version['Quote']); exit;
$quote_model->save($update_version['Quote']);
$current_user = $this->loginUser;
$backup_data['Quote']['vid'] = $quote_id;
$backup_data['Quote']['id'] = null;
$backup_data['Quote']['created'] = date('Y-m-d H:i:s');
$backup_data['Quote']['created_by'] = isset($current_user['id']) ? $current_user['id'] : '0';
unset($backup_data['WorkOrder']);
unset($backup_data['PurchaseOrder']);
$backup_data_all = $backup_data;
unset($backup_data['QuoteStatus']);
unset($backup_data['CabinetOrder']);
unset($backup_data['QuoteInstallerPaysheet']);
unset($backup_data['CabinetOrderItem']);
unset($backup_data['Customer']);
unset($backup_data['User']);
unset($backup_data['UserCreated']);
unset($backup_data['Invoice']);
unset($backup_data['GraniteOrder']);
unset($backup_data['GraniteOrderItem']);
// pr($backup_data);exit;
$flag = $quote->save($backup_data['Quote'], false);
$backup_data['Quote']['vid'] = $quote_id;
// old quote id
$quote_id = (int) $quote->id;
// new quote id
if (isset($this->request->data['QuoteStatus']) && !empty($this->request->data['QuoteStatus'])) {
$this->request->data['QuoteStatus']['quote_vid'] = $quote_id;
}
$backup_data['Quote']['id'] = $quote_id;
// Quote Installer Paysheet
foreach ($backup_data_all['QuoteInstallerPaysheet'] as $index => $value) {
$backup_data_all['QuoteInstallerPaysheet'][$index]['id'] = null;
$backup_data_all['QuoteInstallerPaysheet'][$index]['quote_id'] = $quote_id;
}
App::import('Model', 'QuoteManager.QuoteInstallerPaysheet');
$QuoteInstallerPaysheet = new QuoteInstallerPaysheet();
$QuoteInstallerPaysheet->saveAll($backup_data_all['QuoteInstallerPaysheet']);
// Quote Status
foreach ($backup_data_all['QuoteStatus'] as $index => $value) {
$backup_data_all['QuoteStatus'][$index]['id'] = null;
$backup_data_all['QuoteStatus'][$index]['quote_id'] = $quote_id;
$backup_data_all['QuoteStatus'][$index]['quote_vid'] = $backup_data['Quote']['vid'];
}
App::import('Model', 'QuoteManager.QuoteStatus');
$QuoteStatus = new QuoteStatus();
$QuoteStatus->saveAll($backup_data_all['QuoteStatus']);
if (!empty($backup_data_all['GraniteOrder'])) {
// Granite Order
foreach ($backup_data_all['GraniteOrder'] as $index => $value) {
$backup_data_all['GraniteOrder'][$index]['id'] = null;
$backup_data_all['GraniteOrder'][$index]['quote_id'] = $quote_id;
}
App::import('Model', 'QuoteManager.GraniteOrder');
$graniteOrder = new GraniteOrder();
$graniteOrder->saveAll($backup_data_all['GraniteOrder']);
// Granite Order Item
foreach ($backup_data_all['GraniteOrderItem'] as $index => $value) {
$backup_data_all['GraniteOrderItem'][$index]['id'] = null;
$backup_data_all['GraniteOrderItem'][$index]['quote_id'] = $quote_id;
$backup_data_all['GraniteOrderItem'][$index]['granite_order_id'] = $graniteOrder->id;
}
App::import('Model', 'QuoteManager.GraniteOrderItem');
$graniteOrderItem = new GraniteOrderItem();
$graniteOrderItem->saveAll($backup_data_all['GraniteOrderItem']);
}
if (!empty($backup_data_all['CabinetOrder'])) {
// Cabinet Order
foreach ($backup_data_all['CabinetOrder'] as $index => $value) {
$backup_data_all['CabinetOrder'][$index]['id'] = null;
$backup_data_all['CabinetOrder'][$index]['quote_id'] = $quote_id;
}
App::import('Model', 'QuoteManager.CabinetOrder');
$CabinetOrder = new CabinetOrder();
$CabinetOrder->saveAll($backup_data_all['CabinetOrder'], false);
}
// Cabinet Order Item
// foreach ($backup_data_all['CabinetOrderItem'] as $index => $value) {
// $backup_data_all['CabinetOrderItem'][$index]['id'] = null;
// $backup_data_all['CabinetOrderItem'][$index]['quote_id'] = $quote_id;
//// $backup_data_all['CabinetOrderItem'][$index]['cabinet_order_id'] = $CabinetOrder->id;
//.........这里部分代码省略.........
示例9: reset_quote_cabinets
/**
* add method
*
* @return void
*/
public function reset_quote_cabinets($quote_id)
{
$quote_cabinets = array();
App::import("Model", "QuoteManager.Quote");
$quote_model = new Quote();
$quote = $quote_model->read(null, $quote_id);
$drawer = $this->request['data']['Global']['drawer'];
$drawer_slide = $this->request['data']['Global']['drawer_slide'];
$delivery = $this->request['data']['Global']['delivery'];
$installation = $this->request['data']['Global']['installation'];
$is_interior_melamine = $this->request['data']['Global']['is_interior_melamine'];
$quote['Quote']['drawer'] = $drawer;
$quote['Quote']['drawer_slide'] = $drawer_slide;
$quote['Quote']['delivery'] = $delivery;
$quote['Quote']['installation'] = $installation;
$quote['Quote']['is_interior_melamine'] = $is_interior_melamine;
$quote_model->save($quote);
$this->CabinetOrder->deleteAll(array('quote_id' => $quote_id));
if (isset($this->request['data']['CabinetOrder']) && is_array($this->request['data']['CabinetOrder']) && !empty($this->request['data']['CabinetOrder'])) {
foreach ($this->request['data']['CabinetOrder'] as $cabinet) {
if ($cabinet['temporary']) {
continue;
// skip the not saved one
}
if ($cabinet['temporary_delete']) {
unset($cabinet['temporary_delete']);
}
$cabinet['quote_id'] = $quote_id;
switch ($cabinet['resource_type']) {
case 'cabinet':
$resource_id = $cabinet['resource_id'];
// $resource_type = $cabinet['resource_type'];
$cabinet_color = $cabinet['cabinet_color'];
$material_id = $cabinet['material_id'];
$door_id = $cabinet['door_id'];
$door_color = $cabinet['door_color'];
$quote_cabinets[] = $cabinet + array('quote_id' => $quote_id);
break;
case 'custom_panel':
case 'custom_door':
$cabinet['resource_id'] = '0';
$quote_cabinets[] = $cabinet;
break;
default:
$quote_cabinets[] = $cabinet;
break;
}
}
$this->CabinetOrder->saveAll($quote_cabinets);
}
$this->redirect(FULL_BASE_URL . $this->webroot . 'quote_manager/quotes/detail/' . $quote_id . '#quote-detail');
}
示例10: actionQuickCreate
public function actionQuickCreate()
{
if (isset($_POST['Quote'])) {
foreach ($_POST as $key => $arr) {
$pieces = explode("_", $key);
if (isset($pieces[0]) && $pieces[0] == 'autoselect') {
$newKey = $pieces[1];
if (isset($_POST[$newKey . "_id"]) && $_POST[$newKey . "_id"] != "") {
$val = $_POST[$newKey . "_id"];
} else {
$field = Fields::model()->findByAttributes(array('fieldName' => $newKey));
if (isset($field)) {
$type = ucfirst($field->linkType);
if ($type != "Contacts") {
eval("\$lookupModel={$type}::model()->findByAttributes(array('name'=>'{$arr}'));");
} else {
$names = explode(" ", $arr);
$lookupModel = Contacts::model()->findByAttributes(array('firstName' => $names[0], 'lastName' => $names[1]));
}
if (isset($lookupModel)) {
$val = $lookupModel->id;
} else {
$val = $arr;
}
}
}
$model->{$newKey} = $val;
}
}
// $this->render('test', array('model'=>$_POST));
$model = new Quote();
$oldAttributes = $model->attributes;
foreach (array_keys($model->attributes) as $field) {
if (isset($_POST['Quote'][$field])) {
$model->{$field} = $_POST['Quote'][$field];
$fieldData = Fields::model()->findByAttributes(array('modelName' => 'Quotes', 'fieldName' => $field));
if ($fieldData->type == 'assignment' && $fieldData->linkType == 'multiple') {
$model->{$field} = Accounts::parseUsers($model->{$field});
} elseif ($fieldData->type == 'date') {
$model->{$field} = $this->parseDate($model->{$field});
}
}
}
$contacts = $_POST['associatedContacts'];
// get contacts
$contact = Contacts::model()->findByPk($contacts[0]);
$model->associatedContacts = $contact->id;
$redirect = $_POST['redirect'];
// get product names
$allProducts = Product::model()->findAll(array('select' => 'id, name, currency'));
$productNames = array(0 => '');
foreach ($allProducts as $product) {
$productNames[$product->id] = $product->name;
$productCurrency[$product->id] = $product->currency;
}
$currency = Yii::app()->params->currency;
// get products
if (isset($_POST['ExistingProducts'])) {
$ids = $_POST['ExistingProducts']['id'];
$prices = $_POST['ExistingProducts']['price'];
$quantities = $_POST['ExistingProducts']['quantity'];
$adjustments = $_POST['ExistingProducts']['adjustment'];
$products = array();
foreach ($ids as $key => $id) {
if ($id != 0) {
// remove blanks
$products[$key]['id'] = $id;
$products[$key]['name'] = $productNames[$id];
$products[$key]['price'] = $prices[$key];
$products[$key]['quantity'] = $quantities[$key];
if (strchr($adjustments[$key], '%')) {
// percent adjustment
$products[$key]['adjustment'] = floatval(str_replace("%", "", $adjustments[$key]));
$products[$key]['adjustmentType'] = 'percent';
} else {
$products[$key]['adjustment'] = $adjustments[$key];
$products[$key]['adjustmentType'] = 'linear';
}
}
}
} else {
$products = array();
}
if (!empty($products)) {
$currency = $productCurrency[$products[0]['id']];
}
$model->currency = $currency;
$model->createDate = time();
$model->lastUpdated = time();
$model->createdBy = Yii::app()->user->getName();
$model->updatedBy = Yii::app()->user->getName();
if ($model->save()) {
$changes = $this->calculateChanges($oldAttributes, $model->attributes, $model);
$this->updateChangelog($model, $changes);
// tie contacts to quote
/*
foreach($contacts as $contactid) {
$relate = new Relationships;
$relate->firstId = $model->id;
$relate->firstType = "quotes";
//.........这里部分代码省略.........
示例11: die
if (!$quotes) {
die('no_pending_quotes');
break;
}
require classes_dir . 'quote.php';
echo 'Approving: ';
foreach ($quotes as $quoteid) {
$quote = new Quote();
$quote->permaid = $quoteid['permaid'];
if (!$quote->read()) {
continue;
}
printf('%s ', $quote->permaid);
$push->hit(sprintf(_('New quote: %s - %s'), $quote->permalink, $quote->excerpt));
$quote->status = 'approved';
$quote->save(false);
unset($quote);
}
break;
case 'privacy_login':
$db->query('UPDATE sites SET privacy_level = 2 WHERE db = :db', array(array(':db', $settings->db, PDO::PARAM_STR)));
break;
case 'privacy_hide_all':
$db->query('UPDATE sites SET privacy_level = 1 WHERE db = :db', array(array(':db', $settings->db, PDO::PARAM_STR)));
break;
case 'privacy_unhide_all':
$db->query('UPDATE sites SET privacy_level = 0 WHERE db = :db', array(array(':db', $settings->db, PDO::PARAM_STR)));
break;
case 'privacy_show_all':
$db->query('UPDATE sites SET privacy_level = -1 WHERE db = :db', array(array(':db', $settings->db, PDO::PARAM_STR)));
break;
示例12: actionSave
public function actionSave()
{
$user = Yii::app()->user->getProfile();
$quoteText = Yii::app()->getRequest()->getParam('text', null);
if (!$quoteText === null) {
return false;
}
$blockId = Yii::app()->getRequest()->getParam('blockId', null);
if ($blockId !== null) {
$arr = explode('-', $blockId);
$blockId = key_exists(0, $arr) ? (int) $arr[0] : 0;
$block = Block::model()->published()->findByPK($blockId);
if ($block === false) {
return false;
}
} else {
return false;
}
// Создаем и сохраняем цитату
$quote = new Quote();
$quote->user_id = $user->id;
$quote->block_id = $block->id;
$quote->content = $quoteText;
if ($quote->save()) {
// Общее кол-во цитат
$totalCount = Quote::model()->user($user->id)->program($quote->course_type_id)->count();
// Возвращаем ответ
$resp = array('status' => 1, 'data' => array('id' => $quote->id, 'text' => $quote->getContent(), 'url' => $quote->getUrl(), 'totalCount' => $totalCount));
Yii::app()->ajax->raw($resp);
} else {
$resp = array('status' => 0, 'error' => 'Ошибка сохранения.');
Yii::app()->ajax->raw($resp);
}
}
示例13: addQuote
public function addQuote()
{
$act = 'add';
if (Input::has('submit')) {
$rules = array('quote' => 'required');
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes()) {
$quote = new Quote();
$quote->quote = Input::get('quote');
$quote->date = Input::get('date');
$quote->save();
return Redirect::to('admin/rkmquote')->with('sukses', 'Rekam data berhasil!');
} else {
return Redirect::to('admin/rkmquote')->withInput()->withErrors($validator);
}
} else {
return View::make('admin.quote', compact('act'));
}
}
示例14: switch
if (isset($params[1])) {
switch ($params[1]) {
case 'post':
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
redir(sprintf('%ssubmit', $settings->base_url));
}
$quote = new Quote();
$quote->nick = $_POST['nick'];
$quote->ip = $session->ip;
$quote->text = $_POST['text'];
$quote->comment = $_POST['comment'];
$quote->hidden = isset($_POST['hidden']) && $_POST['hidden'] == 'on';
$quote->status = $session->level == 'admin' ? 'approved' : 'pending';
$quote->api = 1;
// web
$permaid = $quote->save();
if ($permaid === false) {
redir(sprintf('%ssubmit/invalid', $settings->base_url));
}
if ($quote->status == 'approved') {
redir(sprintf('%s%s', $settings->base_url, $permaid));
} else {
redir(sprintf('%ssubmit/sent', $settings->base_url));
}
break;
case 'invalid':
$html->do_sysmsg(_('Oops!'), _('Your quote has not been sent. Maybe it was too short?'), 200);
break;
case 'sent':
$html->do_sysmsg(_('Quote sent!'), _('Your quote has been submitted and is now pending approval!'), 200);
break;
示例15: fire
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$this->line('Lets start our migration.');
//Migrate Groups to Roles
$groups = DB::connection('oldmysql')->table('groups');
$this->line($groups->count() . ' groups[\'s] were found in the legacy database');
foreach ($groups->get() as $group) {
$role = new Role();
$role->name = $group->group;
$role->save();
}
//Migrate Users
$users = DB::connection('oldmysql')->table('users');
$this->line($users->count() . ' user[\'s] were found in the legacy database');
foreach ($users->get() as $user) {
$this->line('Migrating user: ' . $user->username);
$newuser = new User();
$newuser->id = $user->id;
$newuser->username = $user->username;
$newuser->email = $user->email;
$newuser->save();
//Migrate there group to a role
$group = DB::connection('oldmysql')->table('groups')->where('id', $user->group)->first();
$myrole = Role::where('name', $group->group)->first();
$newuser->roles()->attach($myrole);
$this->line('Adding user to role: ' . $group->group);
}
//Migrate Users
$quotes = DB::connection('oldmysql')->table('quotes');
$this->line($quotes->count() . ' quote[\'s] were found in the legacy database');
foreach ($quotes->get() as $quote) {
$this->line('Migrating quote: #' . $quote->id);
$newquote = new Quote();
$newquote->timestamps = false;
$newquote->id = $quote->id;
$newquote->title = $quote->title;
$newquote->quote = $quote->quote;
$user = User::find($quote->userid);
$newquote->user()->associate($user);
$newquote->status = $quote->approved;
$newquote->created_at = date('Y-m-d H:i:s', $quote->timestamp);
$newquote->updated_at = date('Y-m-d H:i:s', $quote->timestamp);
$newquote->save();
}
$votes = DB::connection('oldmysql')->table('votes');
$this->line($votes->count() . ' vote[\'s] were found in the legacy database');
foreach ($votes->get() as $vote) {
$user = User::find($vote->userid);
$quote = Quote::find($vote->quoteid);
if ($user && $quote) {
if ($vote->vote == 1) {
$this->line($user->username . ' voted up #' . $quote->id);
} else {
$this->line($user->username . ' voted down #' . $quote->id);
}
if ($quote) {
$vuser = $quote->voted()->whereUserId($vote->userid)->first();
if (!$vuser) {
$quote->voted()->attach($user, array('vote' => $vote->vote));
} else {
$vuser->pivot->vote = $vote->vote;
$vuser->pivot->save();
}
}
//Our confidence has changed in this quote.
$quote->updateVoteConfidence();
} else {
if (!$quote) {
$this->line('Vote #' . $vote->id . ' could not be imported because the quote doesn\'t exist');
}
if (!$user) {
$this->line('Vote #' . $vote->id . ' could not be imported because the user doesn\'t exist');
}
}
}
}