I am using a separate table to generate invoice numbers.
The code i am using is :
Branch::where('id', $branch_id)->update([
'piref' => DB::raw('piref+1')
]);
$piref = Branch::where('id', $branch_id)->get('piref');
$piref = $piref[0]['piref'];
My question is if the code is wrapped in a transaction. Is this approach safe ?
I tried to use Laravel Increments() but it does not return the newly generated number.
Model method increment() increments property of model and column value in database.
$branch = Branch::find($branch_id);
$branch->increment('piref');
$piref = $branch->piref;
Related
Hello I am a beginner in using Codeigniter. What I want is to update a data in Codeigniter with an OR condition to the ID.
Here is my MySQL query that I want to make happen:
Update message_received SET is_read = 1 WHERE msg_id = 3 OR parent_id = 3
I tried something like this:
$this->query->update_array('message_received', array('msg_id' => $_POST['read_my_message'],'parent_id' => $_POST['read_my_message']) , array('is_read'=>1));
You can use or_where to apply OR condition in CodeIgniter, I've written a possible solution for your question(Reference).
See if it helps you.
$msg = $this->input->post('read_my_message'); // get the post data
$this->db->set('is_read', 1); // set the value of column
$this->db->where('msg_id', $msg); // first condition
$this->db->or_where('parent_id', $msg); // second contion
$this->db->update('message_received'); // table name
// Produces:
/* UPDATE `message_received` SET `is_read` = 1 WHERE `msg_id` = '$msg' OR `parent_id` = '$msg' */
You can apply OR. The references https://www.codeigniter.com/userguide3/database/query_builder.html
Right to the point.
I need to update a field in the database using the field to calculate the new value first.
E.g of fields: https://i.stack.imgur.com/FADH6.jpg
Now I am using the Joomla updateObject function. my goal is to take the "spent" value from the DB table without using a select statement.
Then I need to calculate a new value with it like (spent + 10.00) and update the field with the new value. Check out the code below:
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($object->spent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The bit which i need to make the calculation on is
$object->spent = ($object->spent - $item['total']);
I realise I can use a seperate insert statement but I am wondering if there is a better way. Any help is much appreciated.
It needs to work like this, WITHOUT THE SELECT (working example)
$query = $db->getQuery(true);
$query->select($db->quoteName('spent'));
$query->from($db->quoteName('#__mytable'));
$query->where($db->quoteName('catid')." = ". $item['category']);
// Reset the query using our newly populated query object.
$db->setQuery($query);
$oldspent = $db->loadResult();
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($oldspent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The sticking point with trying to use updateObject('#__mytable', $object, 'catid'); is that your query logic needs to reference the column name in the calculation to assign the "difference" as the new value. The raw mysql query syntax to update a column value with the value minus another value is like:
"`spent` = `spent` - {$item['total']}"
updateObject() will convert spent - {$item['total']} to a literal string, the database will expect a numeric value, so UPDATE results in a 0 value recorded. In other words, $db->getAffectedRows() will give you a positive count and there will be no errors generated, but you don't get the desired mathematical action.
The workaround is to discard updateObject() as a tool and build an UPDATE query without objects -- don't worry it's not too convoluted. I'll build in some diagnostics and failure checking, but you can remove whatever parts that you wish.
I have tested the following code to be successful on my localhost:
$db = JFactory::getDBO();
try {
$query = $db->getQuery(true)
->update($db->quoteName('#__mytable'))
->set($db->quoteName("price") . " = " . $db->qn("price") . " - " . (int)$item['total'])
->where($db->quoteName("catid") . " = " . (int)$item['category']);
echo $query->dump(); // see the generated query (but don't show to public)
$db->setQuery($query);
$db->execute();
if ($affrows = $db->getAffectedRows()) {
JFactory::getApplication()->enqueueMessage("Updated. Affected Rows: $affrows", 'success');
} else {
JFactory::getApplication()->enqueueMessage("Logic Error", 'error');
}
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage("Query Syntax Error: " . $e->getMessage(), 'error'); // never show getMessage() to public
}
Here is a StackOverflow page discussing the mysql subtraction logic: update a column by subtracting a value
I'm new to laravel. I have one income table in the database and I want to maintain the total amount of users but there is a condition if the same user adds new deal_price then all the column will be updated except total and total will be updated like old deal_price+new deal_price.
this my controller
public function storeincome(Request $request){
$date=$request->get('date');
$parse_date=Carbon::parse($date)->format(' d-m-y H:i');
$party_name = $request->Input('party_name');
$deal_price = $request->Input('deal_price');
$mode = $request->Input('mode');
$slug = Str::slug($party_name, '');
$total = $request->Input('deal_price');
$data = array('date'=>$parse_date,'party_name'=>$party_name,'deal_price'=>$deal_price,'mode'=>$mode,'party_slug'=>$slug,'total'=>$total);
Income::insert($data);
return redirect(route('admin.dashboard'))->with('success', trans('message.success.create'));
}
this my table colums
Thanks.
Just update other columns normally and while updating the column 'total', fetch the value of deal_price(old) from your database and store it in a variable ($old_deal_price).
Now, just add the old_deal_price ($old_deal_price) and new_deal_price ($request->deal_price) and update that value in your 'total' field.
$total = ($old_deal_price) + ($request->deal_price);
Goodluck!
I have a function in codeigniter that i want to use to update two tables. This is the code
if($loss_making_trade_amount > 5 && $loss_making_trade_amount < 20){
$user_data = array(
'trading_balance' => $trading_balance_float - 0.50
);
$data = array(
'trade_consequence' => '0.50',
'loss_in_amounts_cron_status' => 'seen'
);
$where = "id='$rid'";
$where_trading_balance = "email='$email'";
$this->db->where($where);
$this->db->set($data);
$this->db->update('mailbox_ke_01', $data);
//update users table at this level
$this->db->where($where_trading_balance);
$this->db->set($user_data);
$this->db->update('users', $user_data);
}
Will i be able to update the tables in the way i have done or will $this be pointing to the first table when updating the second table?.
Your code looks fine, once a query ran - you don't have to be worry about because the Query Builder resets itself after every query if it is finished - or dies in case of a DB Error.
You can take a closer look here
The documentation also clearly suggests that the query runs if the update function gets called.
$this->db->update() generates an update string and runs the query based on the data you supply.
For more information read the documentation here
The only thing i would change are your where clauses:
instead of
$where = "id='$rid'";
$this->db->where($where);
you should use the where function of the Querybuilder properly
$this->db->where("id", $rid);
The same applies for your $where_trading_balance
I am getting a array to my model. Say array has an value 1 and 2.
Now I need to update this to a single column 1,2 so that column will look like this
Column
1,2
foreach($x as $y){
$this->db->where('column',4);
$this->db->set('id',$data);
$this->db->update('table');
}
But this is only update 2, it is omitting 1. Where am i going wrong ?
If you want to save multiple values in a column put them in
an array and serialize them. Than save it in column.
Make the column type text.
$array['name'] = 'test';
$array['otherinfo'] = 'otherinfo';
$data = serialize($array);
foreach($x as $y)
{
$this->db->where('column',4);
$this->db->set('id',$data);
$this->db->update('table');
}
When you select you can unserialize the array using unserialize();
Use implode
For example:
$data = [1,2]
$comma_data = implode(",", $data)
Then update column with $comma_data
I was having wrong data type, I figured it out.