I have a database record with a uniqueID/PrimaryKe (OrderNumber)
I want to update the record with new data for that same PrimaryKey, OrderNumber.
My Controller is:
$data = array(
'CustomerName' => $this->input->post('customer'),
'CustomerAccountCode' => $this->input->post('accountcode'),
'PeriodStart' => substr($this->input->post('period'), 0,10),
'OrderUnitOfMeasure' => $this->input->post('buom'),
'CreditLimit' => $this->input->post('creditlimit'),
'BalanceBeforeOrder' => $this->input->post('currentbalance'),
'BalanceAfterOrder' => $this->input->post('newbalance'),
'OrderLines' => $this->input->post('orderlines'),
'TotalCost' => $this->input->post('grandtotal'),
'AverageDiscount' => $this->input->post('avediscount'),
'TotalCubes' => $this->input->post('grandtotalcubes'),
'TreatedCubes' => $this->input->post('grandtotaltreatedcubes'),
'SpecialComments' => $this->input->post('specialcomments'),
'CustomerReference' => $this->input->post('customerref'),
'ordernumber' => $this->input->post('ordernumber')
);
$this->sales_model->update_order_data($data);
My model is:
function update_order_data($q){
$this->db->where('CustomerOrderID', 'OrderNumber'); //ordernumber being post input ordernumber in array
$query = $this->db->update('Customer_Order_Summary');
}
So what I want is :
update 'Customer_Order_Summary'
set 'CustomerName'="$this->input->post('customer')",
set 'CustomerAccountCode'="$this->input->post('accountcode')",
//rest of set statements for each column and corresponding post
where 'CustomerOrderID'='OrderNumberInArray'//(post value)
This update statement is not working, any pointers would be appreciated.
Thanks as always,
Remove 'ordernumber' from your $data array and pass it separately
$this->sales_model->update_order_data($this->input->post('ordernumber'),$data);
The query should be like
function update_order_data($key,$q){
$this->db->where('CustomerOrderID', $key);
$query = $this->db->update('Customer_Order_Summary',$q);
}
Try:
function update_order_data($q)
{
$this->db->where('CustomerOrderID', $q['OrderNumber']);
$this->db->update('Customer_Order_Summary',$q);
return $this->db->affected_rows();
}
Note: Usually, in update functions, I have 2 arguments eg:
function update_something($pk,$data)
{
$this->db->where('primary_key', $pk);
$this->db->update('database_table',$data);
return $this->db->affected_rows();
}
Related
I'm trying to update the data of pivot table (i want to change product in the order)
I have :
-product table:
id
name
product_price
created_at
updated_at
-order table:
id
status
user_id
created_at
updated_at
-order_products table:
order_id
product_id
product_price
count
created_at
updated_at
in Order model:
public function product(){
return $this->belongsToMany('App\Product')->withPivot('count');
}
in Prodect model:
public function order(){
return $this->belongsToMany('App\Order');
}
in controller:
public function EditOrder(Request $request , $id){
$order = Order::find($id);
$order->status = $request->status;
$order->user_id = $request->user_id;
$order->update();
$product_ids = $request->products;
$selectedItems = [];
foreach ( $product_ids as $key => $productId) {
$id1 = $key['product_id'];
$product = Product ::find($id);
$count = $key['count'];
$selectedItems[$productId] = ['product_id' => $id1 ];
$selectedItems[$productId] = ['count' => $count];
$selectedItems[$productId] = ['order_id' => $order->id];
$selectedItems[$productId] = ['price' => $product->product_price];
$order->product()->updateExistingPivot($selectedItems);
}
return response()->json([
'message' => 'Success'
],200);
i faced this error :
Illegal offset type in file C:\Users\Acer\Documents\GitHub\easyrest\app\Http\Controllers\ResturantController.php on line 80
I want to update product_id and count in order_products
updateExistingPivot() expects 2 params, the first being the id of the relationship you want to update, the second being the array of columns you wish to update. You're not passing an id, so it's trying to use your array as the id, which is why you're getting the error. Fix your logic:
foreach($product_ids as $key => $productId) {
$id1 = $key['product_id'];
$product = Product::find($id);
$count = $key['count'];
$selectedItems[$productId] = ['product_id' => $id1];
$selectedItems[$productId] = ['count' => $count];
// $selectedItems[$productId] = ['order_id' => $order->id]; // [1]
$selectedItems[$productId] = ['price' => $product->product_price];
$order->product()->updateExistingPivot($productId, $selectedItems[$productId]); // [2]
}
[1]: You can omit order_id; $order->product()->updateExistingPivot() already knows the order_id and you're not updating it, so it's redundant.
[2]: You don't want to pass the entire $selectedItems array, only the sub-array contained in $selectedItems[$productId]
By passing $productId as the first argument of updateExistingPivot(), Laravel knows what row you want to update, and will use the array keys in $selectedItems[$productId] to determine which columns to update to what. I don't know if this will actually update product_id, but if it doesn't, you may need to detach() then attach() the data instead:
foreach($product_ids as $key => $productId) {
$selectedItems[$id1] = ['count' => $count];
$selectedItems[$id1] = ['price' => $product->product_price];
$order->products()->detach($productId);
$order->products()->attach($id1, $selectedItems[$id1]);
}
I need to update the database table according to the edited data.
controller
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->update($request->all());
return back();
}
But nothing happens when I submit the form. When I use dd($request->all()); at the beginning of the function, it correctly shows the edited data as follows.
array:10 [▼
"_method" => "patch"
"_token" => "gOCL4dK6TfIgs75wV87RdHpFZkD7rBpaJBxJbLHF"
"editname" => "SUP_EVA_001"
"editdesc" => "des"
"editprice" => "1000.050"
"editlimit" => "1"
"editperunit" => "20.000"
"editexceedunit" => "30.000"
"productid" => "1"
"id" => "1"
]
But database has not been updated.
My table name is Table: subscription_plans and model is SubscriptionPlan
These are the table columns:
protected $fillable = [
'name',
'description',
'price',
'usage_limit',
'charge_per_unit',
'charge_per_unit_exceed',
'is_limit_exceed_considered',
'product_id'
];
Any idea on how to solve it or what I have done wrong?
If your solution did not work, try the 1by1 like this.
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->_method = $request->_method;
$subscriptionplan->_token = $request->_token;
$subscriptionplan->editname = $request->editname;
$subscriptionplan->editdesc = $request->editdesc;
$subscriptionplan->editprice = $request->editprice;
$subscriptionplan->editlimit = $request->editlimit;
$subscriptionplan->editperunit = $request->editperunit;
$subscriptionplan->editexceedunit = $request->editexceedunit;
$subscriptionplan->productid = $request->productid;
$subscriptionplan->save();
return back();
}
In order for Laravel to automatically fill the model attributes, the indexes of the array passed to the fill method must correspond to your model attributes names.
Also, instead of
$subscriptionplan->update($request->all());
Use
$subscriptionplan->fill($request->all());
Then save the subscription plan with $subscriptionplan->save();
I have array that I have to pass into pagination. So how can i convert the array to Object ORM to set into pagination?
I can't $this->paginate = []; because I have to apply some foreach and conditions that's why i did first find all.
$allProductData = $this->PurchaseRequisitionProducts->find('all',[
'contain' => ['PurchaseRequisition','PurchaseOrderProducts'=>function($c){
if($c==null){ return null; }
return $c->where(['PurchaseOrderProducts.id IS NOT NULL']);
},'PurchaseOrderProducts.PurchaseOrder'=>function($p){
return $p->where(['PurchaseOrder.id IS NOT NULL'])
->where(['PurchaseOrder.is_approve'=>"Y"])
//->where(['PurchaseOrder.status'=>1])
->where(['PurchaseOrder.po_type'=>1]);
},'PurchaseOrderProducts.PurchaseOrder.CompanyMaster'] ,
'conditions'=>[$condn,$conditions,'PurchaseRequisition.ready_for_inquiry'=>'Y','PurchaseRequisition.owner_company_id'=>$ownercomp],
'order'=>["PurchaseRequisitionProducts.id"=>"desc"],
])->toArray();
if($allProductData){
foreach($allProductData as $key1=>$prProd){
if(isset($prProd['purchase_order_products'])){
$supplier=[];
foreach($prProd['purchase_order_products'] as $key2=>$poProd){
$supplier[]=$poProd['purchase_order']['supplier_id'];
//debug($supplier);
$companies= $this->CompanyMaster->find('list', [
'keyField' => 'id','valueField' => 'Company_name',
'conditions'=>['id IN'=>$supplier],
])->toArray();
$allProductData[$key1]['supplier']=$companies;
}
}
}
}
$pr_product = $this->paginate($allProductData)
is there any way to ignore the first result record in Yii2 at a query? I have a list of numbers that represents a client. For designing purposes i had to query the first record separatly but now i have it duplicated. My questin is how can I query in Yii2 to ignore the first result?
Regards,
Gábor
The second find is the query where i need to ignore the first result:
public function actionGeneratePage() {
public function actionGeneratePage() {
$behivott = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(1)
->all();
$sorszamok = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(4)
->all();
$reklam = Reklam::find()->all();
return $this->render('generatePage', [
'sorszamok' => $sorszamok,
'reklam' => $reklam,
'behivott' => $behivott,
]);
}
You use offset() to skip the first record:
$sorszamok = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(4)
->offset(1)
->all();
Also you can use a single query to get both $behivott and $sorszamok with array_shift:
$sorszamok = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(5)
->all();
$behivott = array_shift($sorszamok);
Apologies in advance if i use the wrong definition of a word...I am using SimpleCart to pass $.Post variables to a PHP page. If i print the array i get
Array ( [currency] => CAD [shipping] => 0 [tax] => 1.69 [taxRate] => 0.13 [itemCount] => 3 [item_name_1] => Dinner Plate [item_quantity_1] => 1 [item_price_1] => 5 [item_options_1] => code: 110 [item_name_2] => Side Plate [item_quantity_2] => 1 [item_price_2] => 4 [item_options_2] => code: 125 [item_name_3] => Mixing Bowl [item_quantity_3] => 1 [item_price_3] => 4 [item_options_3] => code: 66 )
What I am struggling with (and going around in circles) is a method to do the following..
Explode the [item_options] variable to strip out the CODE: part of the value and just leave the numeric section.
concatenate these values into a string so i can use a SELECT statement to only pull records that have an ID passed in the [item.options].
I understand how to explode a single parameter, but cannot work out how to loop through the array, explode the key and create the value i need for the SQL.
Any help or pointers to relevant tutorials would be much appreciated
$codes = array();
foreach ($_POST as $key => $value) { // Loop through the $_POST array
if (preg_match('/^item_options_/', $key)) { // And validate the value
$item_arr = explode(' ', $value);
$item_id = $item_arr[1]; // Get the ID number from the value
if (is_numeric($item_id)) { // Validate it
$codes[] = $item_id; // Add it to the array we're building
}
}
}
$codes_string = implode(', ', $codes); // Concatenate them into a string that can be used in a SQL IN clause
$sql = "SELECT * from table WHERE id IN ($codes_string)"; // Build the SQL