Laravel update query (Add a value to existing a value) - mysql

I am trying to update a record using Laravel.
I have gone through lot of StackOverflow Questions to check whether this question is already raised.
mysql query : UPDATE students SET total_marks = total_marks + 80 WHERE id = 1
I have to translate this mysql query into Laravel query builder, but couldn't get a solution yet.
Instead of getting the early value from DB before update, Can we update the table with one update query using Laravel Query Builder.
2 Queries way:
$student_marks = Students::select('total_marks')->where('id','=',1);
$current_mark = $student_marks['total_marks']+80;
$update_student_marks = Students::where('id','=',1)->update('total_marks','=',$current_mark);
How to update a record like this with single query builder in Laravel.

I think you need to make a few adjustments to your query.
First, you need to select the student correctly and than use Eloquent to call save method on it after setting the property to the correct value. I assume you are on Laravel 6.
$student_marks = Students::find($id);
$student_marks->total_marks += 80;
$student_marks->save();
Please, take a look at Laravel docs:
https://laravel.com/docs/6.x/eloquent
The reading takes some time but its definitely worth it. You will learn how to deal with eloquent and make your code better by using the most appropriate techniques.

You can use the save function for this.
$student_marks = Students::select('total_marks')->where('id','=',1);
$student_marks->total_marks += 80; //or $student_marks->total_marks = $student_marks->total_marks + 80;
$student_marks->save();

Pass update data as array
Try this way
$update = array('total_marks'=>$current_mark);
$update_student_marks = Students::where('id','=',1)->update($update);

Related

Update Case-Sensitive DB Field In Laravel 5.3 With Postgres

I am trying to update a database column field with raw SQL in laravel. It's important to mention that the update code was written to MySQL drive but now I use Postgres. The column name is dayID. So the update code is:
DB::update("update table set travel = ... WHERE dayID = {$this->dayID}");
I must use raw SQL because I make some updates to polygon types.
The problem is that laravel automatically transforms the dayID to dayid so I get an error:
column "dayid" does not exist
I tried to set a variable in order to use it in update query but it also failed with the same error:
$var = "dayID";
DB::update("update table set travel = ... WHERE ".$var." = {$this->dayID}");
How can I fix it?
Please try DB::table with update below:
DB::table('table_name')
->where('dayID', $this->dayID)
->update(['travel' => '...']);
Laravel document :
https://laravel.com/docs/5.3/queries#updates

How do raw query in kohana freamwork

I want make package with list of query.
It is update query like as:
UPDATE table
SET column = XXX
WHERE column = XXX AND column2 = XXX;
UPDATE table
SET column = XXX
WHERE column = XXX AND column2 = XXX;
UPDATE table
SET column = XXX
WHERE column = XXX AND column2 = XXX;
I have these 1000 queries in one package. Now I want make do queries.
I try do it, but unsuccessfully, because every time I get an error like that:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near...
I copy this query and past to phpmyadmin and I do it. These queries work!
I have a variable with prepared queries and I trying to do it in different way.
Database::instance()->query(NULL,$sql);
DB::query(5,$sql)->execute();
DB::query(Database::UPDATE,DB::expr($sql))->execute();
DB::query(Database::UPDATE,$sql)->execute();
but it does not work ;/
Anyone know how do it?
Just call method query from instance of database:
/** #var Database $db */
$db = Database::instance();
$db->query(Database::UPDATE, 'UPDATE table SET column = XXX WHERE column = XXX AND column2 = XXX;');
But if you want execute multiple SQL statements in one query it's impossible out of box. By default Kohana use old mysql API and mysql_query do not support multiple queries in a single call.
It you want use multiple SQL statements i know 3 way:
Some times ago for Kohana i saw module for mysqli support, you can try to find him and modify: add to it new method which will be use http://php.net/manual/en/mysqli.multi-query.php mysqli::multi_query can execute multiple SQL statements in one query.
Or you can switch to using PDO. For this you must make changes in your database config file, according Kohana's documentation, add map for columns in models.
Or create new PDO connection in set up it only for this query (if you don't use transaction it will be more easy, than variant 2).
Also for variant 2 and 3 you must set up some PDO settings: https://stackoverflow.com/a/6461110/419665
P.S. For call database instance by config name:
Database::instance('config_name');

Symfony 2 - Doctrine ORM Update query not working

I am trying to update a mysql table with following query using Doctrine. But the table is not get updated. Also below code didnt throw any error. I am totally confused. If i run the query, taken from getDQL() method, in mysql directly it showing 0 rows updated becuase of inproper qoutes. it is working after placed proper qoutes for values in the query. Need help to solve this puzzle.
Since i am new to doctrine, i will use the examples give in querybuilder class file.
$support = $this->createQueryBuilder('p')
->update('gcns', 'g')
->set("g.isActive", "0")
->andWhere("g.issn='".$issn."'");
Do you ever execute the query or are you just building it? You should have something along these lines to execute it:
$support->getQuery()->getSingleScalarResult();
If i run the query, taken from getDQL() method, in mysql directly it showing 0 rows updated becuase of inproper qoutes.
getDQL() returns DQL not SQL, so it will have improper quotesif you try to run it directly inside MySQL, but that's expected.
You shouldn't concatenate $issn into your query. You should use parameters instead:
$qb = $this->createQueryBuilder()
$support = $qb->update('gcns', 'g')
->set('g.isActive', '0')
->andWhere( $qb->expr()->eq('g.issn', ':issn') )
->setParameter( 'issn', $issn )
->getQuery()->getSingleScalarResult()
;

DBIx::Class update only one row

I am using DBIx::Class and I would like to only update one row in my table. Currently this is how I do it:
my $session = my_app->model("DB::Session")->find(1);
$session->update({done_yn=>'y',end_time=>\'NOW()'});
It works, but the problem is that when it does find to find the row, it does this whole query:
SELECT me.id, me.project_id, me.user_id, me.start_time, me.end_time, me.notes, me.done_yn FROM sessions me WHERE ( me.id = ? ): '8'
Which seems a bit much when all I want to do is update a row. Is there anyway to update a row without having to pull the whole row out of the database first? Something like this is what I am looking for:
my_app->model("DB::Session")->update({done_yn=>'y',end_time=>\'NOW()'},{id=>$id});
Where $id is the WHERE id=? part of the query. Does anyone know how to do this? Thanks!
You can run update on a restricted resultset which only matches this single row:
my_app->model("DB::Session")->search_rs({ id=> 1 })->update({done_yn=>'y',end_time=>\'NOW()'});
I suggest you use a DateTime->now object instead of literal SQL for updating the end_time column because it uses the apps servers date and time instead of the database servers and makes your schema more compatible with different RDBMSes.
Do you have a check if the row was found to prevent an error in case it wasn't?
You might want to use update_or_create instead.
You could use the "columns" attribute:
my $session = my_app->model("DB::Session")->find(1, {columns => "id"});

is this the correct way to optimize MySQL Query?

$sql="update users_contain
set
wood_max = (Select building_production from building_level where merge_id=$subPrimaryKey and empire_id=$user_empireID) ,
iron_max = wood_max,
clay_max = wood_max
where user_id = $user_id";
Now there is a question.
will wood_max will always be updated first than iron_max and clay_max. so it is safe to use this way??
i do not want to use inner query for updating the iron_max and clay_max when i know it has same value for all three fields..
According to this documentation, your UPDATE statement works as you want it to: http://dev.mysql.com/doc/refman/5.1/en/ansi-diff-update.html
Test it to be sure, but I think you're fine.