insert data in multiple table with one function in laravel - mysql

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();

Related

importing data from another database based on field value

I have a website where I am trying to setup a page where someone would have to enter a number into a field, which would correspond to a field in the other database, and import (add) the records from that database, into a table of another database, and I am having trouble with that.
I know how to update and add data from table to table within the same database, but just unsure how I would do that from another database.
This is the code that I would use to add data to another table
$data = array();
$keyvalues = array();
$data["Number"] = $values['Number'];
$data["Rider Name"] = $values['Rider Name'];
$data["Horse Name"] = $values['Horse Name'];
$data["Division Name"] = $values['Division Name'];
$data["Level"] = $values['Level'];
$data["Division Type"] = $values['Division Type'];
$data["Show Type"] = $values['Show Type'];
$data["Dressage Test"] = $values['Dressage Test'];
$keyvalues["Number"] = $values['Number'];
if ($values['Number'] = $values['Number']){
DB::Insert("Scoring", $data, $keyvalues );
}
But not sure how I would do it from another database. Any help would be appreciated.

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

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

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()

Getting a bool value from DataTable with linq

I have to fill a DataGrid using a DataTable, and linq. The DataTable contains a MySql table (i am using linq to optimize the program in terms of network traffic), but when the linq tries to get the boolean values from the DataTAble i get an "InvalidCastException" exc. with "The 'OneWay' or 'TwoWay' binging can not work..." text. Is there any way to make it work? (sry for bad eng)
string q = "Select * from `beszallitoi_megrendeles` "
+ "where megrendelt='1' and beerkezett='0' "
+ "order by megrendeles_datuma desc;";
parancs = new MySqlCommand(q, Kapcsolat);
Kapcsolat.Open();
parancs.ExecuteNonQuery();
MySqlDataAdapter mda = new MySqlDataAdapter(parancs);
DataTable dt = new DataTable("beszallitoi_megrendeles");
mda.Fill(dt);
mda.Update(dt);
...
var results = from a in dt.AsEnumerable()
select new
{
AZ = a.Field<int>("AZ"),
MEGRENDEL = a.Field<DateTime>("MEGRENDEL"),
KERTSZDATUM = a.Field<DateTime>("KERTSZDATUM"),
VEVO_CSOPORT = a.Field<string>("VEVO_CSOPORT"),
ROVIDVEVONEV = a.Field<string>("ROVIDVEVONEV"),
GYARTO = a.Field<string>("GYARTO"),
MEGNEVEZES = a.Field<string>("MEGNEVEZES"),
DARAB = a.Field<int>("DARAB"),
MEGJEGYZES = a.Field<string>("MEGJEGYZES"),
RENDSZAM = a.Field<string>("RENDSZAM"),
BRENDSZAM = a.Field<string>("BRENDSZAM"),
ROGNEV = a.Field<string>("ROGNEV"),
BESZALLITO = a.Field<string>("BESZALLITO"),
MEGREND = a.Field<DateTime>("MEGREND"),
VARERK = a.Field<DateTime>("VARERK"),
CSKULD = a.Field<string>("CSKULD"),
MEGJEGY2 = a.Field<string>("MEGJEGY2"),
BMEGREND = a.Field<bool>("BMEGREND"),
BERKDAT = a.Field<DateTime>("BERKDAT"),
BEERK = a.Field<bool>("BEERK")
};
DgUjMegrendeles.ItemsSource = results;
EDIT:
Here is the boolean column: ( i modified the mode from "TwoWay" to "OneWay" then "OneTime" but this way all the rows had true values)
<DataGridCheckBoxColumn Width="45" Header="MREND." Binding="{Binding BMEGREND, Mode=OneTime, UpdateSourceTrigger=PropertyChanged}"/>
The anonymous type you're creating (new { AZ = ... }) has read only properties. You are trying to bind to something using a TwoWay binding mode. You will have to set the binding mode to OneWay or OneTime. You don't show your XAML, however.

Linq to SQL: DISTINCT with Anonymous Types

Given this code:
dgIPs.DataSource =
from act in Master.dc.Activities
where act.Session.UID == Master.u.ID
select new
{
Address = act.Session.IP.Address,
Domain = act.Session.IP.Domain,
FirstAccess = act.Session.IP.FirstAccess,
LastAccess = act.Session.IP.LastAccess,
IsSpider = act.Session.IP.isSpider,
NumberProblems = act.Session.IP.NumProblems,
NumberSessions = act.Session.IP.Sessions.Count()
};
How do I pull the Distinct() based on distinct Address only? That is, if I simply add Distinct(), it evaluates the whole row as being distinct and thusly fails to find any duplicates. I want to return exactly one row for each act.Session.IP object.
I've already found this answer, but it seems to be a different situation. Also, Distinct() works fine if I just select act.Session.IP, but it has a column I wish to avoid retrieving and I'd rather not have to do this by manually binding my datagrid columns.
dgIPs.DataSource =
from act in Master.dc.Activities
where act.Session.UID == Master.u.ID
group act by act.Session.IP.Address into g
let ip = g.First().Session.IP
select new
{
Address = ip.Address,
Domain = ip.Domain,
FirstAccess = ip.FirstAccess,
LastAccess = ip.LastAccess,
IsSpider = ip.isSpider,
NumberProblems = ip.NumProblems,
NumberSessions = ip.Sessions.Count()
};
Or:
dgIPs.DataSource =
from act in Master.dc.Activities
where act.Session.UID == Master.u.ID
group act.Session.IP by act.Session.IP.Address into g
let ip = g.First()
select new
{
Address = ip.Address,
Domain = ip.Domain,
FirstAccess = ip.FirstAccess,
LastAccess = ip.LastAccess,
IsSpider = ip.isSpider,
NumberProblems = ip.NumProblems,
NumberSessions = ip.Sessions.Count()
};
One of the overloads of Enumerable.Distinct accepts an IEqualityComparer instance. Simply write a class that implements IEqualityComparer and which only compares the two Address properties.
Unfortunately, you'll have to give a name to the anonymous class you're using.