What is the equavelent of mysql : SET in laravel 4.2? - laravel

i am new to Laravel and now trying to use transaction in Laravel 4.2
I am trying to replace this Mysql query in laravel.
UPDATE managerStock SET amount = amount + $productAmount WHERE manager_id = '$receiverID' and product_id='$productID
So far i came up with this code
DB::table('distributorStock')->where('distributor_id','=','senderID')->where('manager_id','=','receiverID')->update(array('amount' => ''));
I am looking for your kind help regarding this challenge!
Thanks

if you want to replace bellow mysql query -
UPDATE managerStock SET amount = amount + $productAmount WHERE manager_id = '$receiverID' and product_id='$productID'
Possible answer could be -
$dbData = DB::table('managerStock')->where('manager_id', $receiverID)->where('product_id', $productID)->first();
$dbData->amount = $dbData->amount+$productAmount;
$dbData->save();
for more than one database query as a transaction you can use -
DB::transaction(function() use ($dbData1, $dbData2, $dbData3) {
$dbData1->save();
$dbData2->save();
$dbData3->save();
});

Related

How to update a single value with laravel

Hello i want to update a single value on another table using laravel. This is the code i have done until now but doesnt seem to work:
$amount = Product::findorFail($request->products[$i]);
$total_value = $request->amount[$i] + $amount->amount;
$amount->update(['amount', $total_value]);
dd($total_value);
with dd i see that the result is correct but the update function is not, the query im trying to make is
update table set amount=x where id=y
You have multiple choices. The shortes are:
$amount->update(['amount'=> $amount->amount + request->amount[$i]]);
or
Product::findorFail($request->products[$i])->increment('amount', $request->amount[$i]);
you could change your code like below
$amount = Product::findorFail($request->products[$i]);
$total_value = $request->amount[$i] + $amount->amount;
$amount->amount=$total_value;
$amount->update();
or as mentioned in comments you could use eloquent increment function

Codeigniter updating data with OR condition in ID

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

Eloquent: Do I need to do this query raw?

I'm rewriting parts of legacy software using laravel/eloquent.
my understanding of typical eloquent is good and I've done some projects in laravel but not so much for legacy code.
I'm trying to do this in eloquent which creates 79 rows:
INSERT IGNORE INTO `ps_module_shop` (`id_module`, `enable_device`, id_shop) (SELECT `id_module`, `enable_device`, 555 FROM ps_module_shop WHERE `id_shop` = 1);
I've read you can only do bulk insert with model::insert but I'm not sure how to do so with this query specifically, other than pure sql.
This is how I'm doing it for now, but raw sql feels more elegant for this query:
$blkInsert = [];
$tplModuleShop = ModuleShop::where('id_shop', 1)->get();
foreach($tplModuleShop as $mshop) {
$blkInsert[] = [
'id_module' => $mshop->id_module,
'enable_device' => $mshop->enable_device,
'id_shop' => $shop->id_shop,
];
}
ModuleShop::insert($blkInsert);
Note: I know this is a pivot table, but it is legacy db that uses composite keys so I decided to treat it as its own model.
Honestly this might just be easier using your sql statement... here is my attempt:
DB::table('ps_model_shop')
->insert(DB::table('ps_module_shop')
->select(['id_module', 'enable_device'])
->where('id_shop', 1)
->get()
->map(function($module){
$module['id_shop'] = 555;
})
->toArray()
);
We found a way to do it with DB::select (although still doing the sql part "raw")
$fixCollection = function($collection) {
return json_decode(json_encode($collection), true);
};
ModuleShop::insert(
$fixCollection(
\DB::select("SELECT `id_module`, `enable_device`, {$shop->id_shop} as id_shop FROM ps_module_shop WHERE `id_shop` = 1")
)
);

Adding values in database with query in laravel

I want to add 10 from a current database value.
Current db value = 20;adding = 10;updated value 30;
The following code is not working.
DB::table('employee')->increment('bonus'=>'bonus+10');
Try this:
DB::table('employee')->increment('bonus', 10);
Try this -
DB::table('employee')->increment('bonus', 10);
You can do like this as well:
DB::table('employee')
->where('rowID', 1) // if you to add in a perticular table else comment it for updating entire column's value by adding 10 in it.
->update([
'bonus' => DB::raw('bonus + 10'),
]);
Hope this will help you.

Multiple rows update without select

An old question for Linq 2 Entities. I'm just asking it again, in case someone has came up with the solution.
I want to perform query that does this:
UPDATE dbo.Products WHERE Category = 1 SET Category = 5
And I want to do it with Entity Framework 4.3.1.
This is just an example, I have a tons of records I just want 1 column to change value, nothing else. Loading to DbContext with Where(...).Select(...), changing all elements, and then saving with SaveChanges() does not work well for me.
Should I stick with ExecuteCommand and send direct query as it is written above (of course make it reusable) or is there another nice way to do it from Linq 2 Entities / Fluent.
Thanks!
What you are describing isnt actually possible with Entity Framework. You have a few options,
You can write it as a string and execute it via EF with .ExecuteSqlCommand (on the context)
You can use something like Entity Framework Extended (however from what ive seen this doesnt have great performance)
You can update an entity without first fetching it from db like below
using (var context = new DBContext())
{
context.YourEntitySet.Attach(yourExistingEntity);
// Update fields
context.SaveChanges();
}
If you have set-based operations, then SQL is better suited than EF.
So, yes - in this case you should stick with ExecuteCommand.
I don't know if this suits you but you can try creating a stored procedure that will perform the update and then add that procedure to your model as a function import. Then you can perform the update in a single database call:
using(var dc = new YourDataContext())
{
dc.UpdateProductsCategory(1, 5);
}
where UpdateProductsCategory would be the name of the imported stored procedure.
Yes, ExecuteCommand() is definitely the way to do it without fetching all the rows' data and letting ChangeTracker sort it out. Just to provide an example:
Will result in all rows being fetched and an update performed for each row changed:
using (YourDBContext yourDB = new YourDBContext()) {
yourDB.Products.Where(p => p.Category = 1).ToList().ForEach(p => p.Category = 5);
yourDB.SaveChanges();
}
Just a single update:
using (YourDBContext yourDB = new YourDBContext()) {
var sql = "UPDATE dbo.Products WHERE Category = #oldcategory SET Category = #newcategory";
var oldcp = new SqlParameter { ParameterName = "oldcategory", DbType = DbType.Int32, Value = 1 };
var newcp = new SqlParameter { ParameterName = "newcategory", DbType = DbType.Int32, Value = 5 };
yourDB.Database.ExecuteSqlCommand(sql, oldcp, newcp);
}

Resources