How to save data from a table from another database in Laravel? - mysql

I need to save data from an order table from one database to another through Laravel. I created a function in my controller like this:
public function getMarketplace()
{
$orderoc = OrderOC::orderBy('oc_order.date_added', 'desc')
->join('oc_order_product', 'oc_order_product.order_id', 'oc_order.order_id')
->join('oc_order_history', 'oc_order_history.order_id', 'oc_order.order_id')
->where('oc_order_history.order_status_id', '=', '17')
->get();
foreach($orderoc as $oc){
$ordererp = new Order;
$ordererp->erp_createdid = $oc->created_id;
$ordererp->erp_marketplaceid = 1;
$ordererp->erp_site = rand(1,100000000);
$ordererp->erp_payment_method = $oc->payment_method;
$ordererp->erp_orderdate = $oc->date_added;
$ordererp->erp_orderaprove = $oc->date_added;
$ordererp->erp_billingid = 1;
$ordererp->erp_shippingid = 1;
$ordererp->erp_marketplace = 'Comércio Urbano';
$ordererp->erp_orderquantity = $oc->quantity;
$ordererp->erp_erro = '';
$ordererp->erp_product_ok = 1;
$ordererp->erp_compraId = null;
$ordererp->save();
if(strlen($oc->created_id) == 0){
$oc->created_id = rand(1,10000000);
$oc->save();
}
$orderprod = new OrderProduct;
$orderprod->erp_productid = $oc->product_id;
$orderprod->erp_createdid = $oc->created_id;
$orderprod->erp_model = $oc->model;
$orderprod->erp_quantity = $oc->quantity;
}
}
One table is from my ERP and the other is responsible for receiving OpenCart purchases, but every time I run, the same product appears more than once in my order table.
(It is possible to see through the purchase date, since created_id is created in the controller function)
Does anyone know how to tell me why data is duplicated when inserted inside a foreach? This is not the first time, if you tell me a more robust way of doing the job, I'm grateful. Any suggestion? Thank you in advance!

One possiblity is you put unique validation on a table that receive the data

Related

Problem with loading large MySQL Table into JSON

We have a large MySQL Table (say) 50,000 records or rows. The loading time of all the records is close to 20 mins. By loading I mean the data getting displayed in the browser or in a Javascript Grid - time taken to load this data is around 20 mins. This is creating a big problem for us. We have even tried to return all data in JSON following this approach How to convert result table to JSON array in MySQL still we are facing a prolonged delay in loading.
The query is very much straight forward as shown below. Can anyone help us with any solution to overcome this problem. Thanks in advance!
<?php
include 'includes/xxx.php';
$returnArray = array();
$totalSymptoms = 0;
$matchedSymptomIds = array();
$cutOff = 10;
$runningGlobalSymptomId = "";
$symptomResult = mysqli_query($db,"SELECT * FROM comparison_small WHERE (matched_percentage IS NULL OR matched_percentage >= ".$cutOff.")");
if(mysqli_num_rows($symptomResult) > 0){
while($symRow = mysqli_fetch_array($symptomResult)){
$dataArray = array();
$totalSymptoms++;
if($symRow['current_symptom'] == '1'){
// Global symptom
$runningGlobalSymptomId = $symRow['symptom_id'];
$dataArray['symptom_id'] = $symRow['symptom_id'];
$dataArray['row_id'] = "row".$symRow['symptom_id'];
$dataArray['symptom'] = $symRow['symptom'];
$dataArray['match'] = "";
}else{
// Local symptom
array_push($matchedSymptomIds, $symRow['symptom_id']);
$dataArray['symptom_id'] = $symRow['symptom_id'];
$dataArray['row_id'] = "row".$runningGlobalSymptomId."_".$symRow['symptom_id'];
$dataArray['symptom'] = $symRow['symptom'];
$dataArray['match'] = $symRow['matched_percentage'];
}
$returnArray[] = $dataArray;
}
}

Fetch the details from database using laravel

I am trying to get the details from database and written below Laravel code to fetch the details from two table using join query. But it is taking too much time while fetching the data.
Can you guys help me? So it will take minimum time to fetch the API.
public function getWebsiteVisitorsDetails($businessId, $startTime, $endTime, $filterType){
$chatBotClicked = DB::table('chatbot_website_visitor_detail')
->join('website_visitors_task', 'website_visitors_task.website_session_id', '=', 'chatbot_website_visitor_detail.website_session_id')
->where('website_visitors_task.session_task_perform' , 3)
->where('chatbot_website_visitor_detail.business_id', $businessId);
if($filterType != ApiConstant::ALL_TIME){
$chatBotClicked = $chatBotClicked->whereBetween('website_visitors_task.created_at', [$startTime, $endTime]);
}
$feedbackClicked = DB::table('chatbot_website_visitor_detail')
->join('website_visitors_task', 'website_visitors_task.website_session_id', '=', 'chatbot_website_visitor_detail.website_session_id')
->where('website_visitors_task.session_task_perform' , 2)
->where('chatbot_website_visitor_detail.business_id', $businessId);
if($filterType != ApiConstant::ALL_TIME){
$feedbackClicked = $feedbackClicked->whereBetween('website_visitors_task.created_at', [$startTime, $endTime]);
}
$firstTimeVisitor = DB::table('chatbot_website_visitor_detail')
->select('chatbot_website_visitor_detail.id')
->where('chatbot_website_visitor_detail.business_id', $businessId)
->where('chatbot_website_visitor_detail.from_popup_widget', 1);
if($filterType != ApiConstant::ALL_TIME){
$firstTimeVisitor = $firstTimeVisitor->whereBetween('chatbot_website_visitor_detail.created_at', [$startTime, $endTime]);
}
$returnData['chatbot_clicked'] = $chatBotClicked->count();
$returnData['feedback_clicked'] = $feedbackClicked->count();
$returnData['first_time_user'] = $firstTimeVisitor->count();
}

insert data in multiple table with one function in laravel

I'm trying to add values in multiple tables with the same function but I get an error that the id and product_id can't be null !! even though they are set. Here's my code:
$parentproduct=new Product();
$parentproduct->id=Input::get('id');
$insertedId = $parentproduct->id;
$parentproduct->save();
$product=new ProductsTranslation();
$product->id=Input::get('id');
$product->product_id =Input::get('insertedId');
$product->title=Input::get('title');
$product->content=Input::get('content');
$product->price=Input::get('price');
$product->description_title=Input::get('description_title');
$product->prod_info_title=Input::get('prod_info_title');
$product->prod_info=Input::get('prod_info');
$product->save();
Looks like you need to move a few things around here...
This $insertedId = $parentproduct->id; wont return a value until you've ran `->save().
Also, your second statement is trying to get an Input::('insertedId') but you're setting a variable above.
Try this:
$parentproduct = new Product();
$parentproduct->id = Input::get('id');
$parentproduct->save();
$insertedId = $parentproduct->id;
$product = new ProductsTranslation();
$product->id = Input::get('id');
$product->product_id = $insertedId;
$product->title = Input::get('title');
$product->content = Input::get('content');
$product->price = Input::get('price');
$product->description_title = Input::get('description_title');
$product->prod_info_title = Input::get('prod_info_title');
$product->prod_info = Input::get('prod_info');
$product->save();

How to get last inserted id with insert method in laravel

In my laravel project I am inserting multiple records at time with modelname::insert method. Now I want to get last inserted id of it.I read somewhere when you insert multiple records with single insert method and try to get the last_record_id it will gives you the first id of the last inserted query bunch. But my first question is how to get last record id with following code .If I am able to get first id of the bunch .I ll make other ids for other record by my own using incremental variable.
Code to insert multiple record
if(!empty($req->contract_name) && count($req->contract_name)>0)
{
for($i=0; $i<count($req->contract_name); $i++)
{
$contract_arr[$i]['client_id'] = $this->id;
$contract_arr[$i]['contract_name'] = $req->contract_name[$i];
$contract_arr[$i]['contract_code'] = $req->contract_code[$i];
$contract_arr[$i]['contract_type'] = $req->contract_type[$i];
$contract_arr[$i]['contract_ext_period'] = $req->contract_ext_period[$i];
$contract_arr[$i]['contract_email'] = $req->contract_email[$i];
$contract_arr[$i]['created_at'] = \Carbon\Carbon::now();
$contract_arr[$i]['updated_at'] = \Carbon\Carbon::now();
$contract_arr[$i]['created_by'] = Auth::user()->id;
$contract_arr[$i]['updated_by'] = Auth::user()->id;
if($req->startdate[$i] != ''){
$contract_arr[$i]['startdate'] = date('Y-m-d',strtotime($req->startdate[$i]));
}
if($req->enddate[$i] != ''){
$contract_arr[$i]['enddate'] = date('Y-m-d',strtotime($req->enddate[$i]));
}
}
if(!empty($contract_arr)){
Contract::insert($contract_arr);
}
}
You should be able to call it like this
$lastId = Contract::insert($contract_arr)->lastInsertId();
If i see right, you're using a Model. Direct inserting only shows an success boolean. Try this instead:
Contract::create($contract_arr)->getKey()

Ways to update only modified columns in table using LINQ

I have 20 fields on form, how to update fields modified by user during runtime and how to check which fields have changed so that i can only update those values in table using LINQ. I am working on windows application using C# and VS2010
Please refer the code (Currently i am passing all values, i knw this is not the correct way)
private void UpdateRecord(string groupBoxname)
{
using (SNTdbEntities1 context = new SNTdbEntities1())
{
{
Vendor_Account va = new Vendor_Account();
var Result = from grd in context.Vendor_Account
where grd.Bill_No == dd_billNo.Text
select grd;
if (Result.Count() > 0)
if ((dd_EditProjectName.Text!= "Select") && (dd_billNo.Text!="Select") && (dd_editVendorName.Text!="Select"))
{
foreach (var item in Result)
{
va.Account_ID = item.Account_ID;
}
va.Amount_After_Retention = Convert.ToDecimal(txt_AD_AfterRet.Text);
va.Balance = Convert.ToDecimal(txt_AD_Balance.Text);
va.Bill_Amount = Convert.ToDecimal(txt_AD_BillAmount.Text);
va.Bill_Date = Convert.ToDateTime(dt_AD_BillDate.Text);
va.Bill_No = dd_billNo.Text;
va.Comments = txt_AD_Comments.Text;
va.Paid_Till_Date = string.IsNullOrEmpty(txt_AD_Paid.Text)?0:Convert.ToDecimal(txt_AD_Paid.Text);
va.Project_Name = dd_EditProjectName.Text;
va.Retention_Perc = Convert.ToDecimal(txt_retPerc.Text);
va.Amount_After_Retention = Convert.ToDecimal(txt_AD_AfterRet.Text);
va.Vendor_Name = dd_editVendorName.Text;
va.Vendor_Code = txt_AD_Code.Text;
context.Vendor_Account.ApplyCurrentValues(va);
//context.Vendor_PersonalInfo.AddObject(vpi);
context.SaveChanges();
MessageBox.Show("Information Updated Sucessfully!");
lbl_Warning.Text = "";
entityDataSource1.Refresh();
}
else
{
MessageBox.Show("Vendor Name,Project Name and Bill No cannot be blank!!");
}
}
}
}
Entity framework will do that task.
Since you didn't provide any code, I cannot be precise about the answer but please check those links:
http://msdn.microsoft.com/en-us/library/aa697427(v=vs.80).aspx, section:Manipulating Data and Persisting Changes
http://www.codeproject.com/KB/database/sample_entity_framework.aspx
Note that the SaveChanges() function will update any modification done the records in EF.
Create some field dublicates, and compare value from the form element with the local dublicate, if it was changed than update it.