Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do update query on laravel fluent using db::raw

Tags:

laravel

This is related to one of my question earlier where:

Update table1 field with table2 field value in join laravel fluent

But since this is a different approach now, I will just ask another question:

How do you properly do an update using DB:raw?

I want to update the favorite_contents.type with the value of contents.type, but it doesn't do anything, the static setting of 1 to favorite_contents.expired is working.

This is my code which still doesn't update the type even when the DB::raw was used:

$table = 'favorite_contents'; $contents = DB::table($table)             ->join('contents', function($join) use($table){                 $join->on("$table.content_id", '=', 'contents.id');             })             ->whereIn("$table.content_id",$ids)             ->update(array(                     "$table.expired" => 1             ));  DB::raw("UPDATE favorite_contents, contents SET favorite_contents.type = contents.type where favorite_contents.content_id = contents.id"); 

This is the first code that doesn't update before I resorted to the above code that doesn't work as well:

$table = 'favorite_contents'; $contents = DB::table($table)         ->join('contents', function($join) use($table){             $join->on("$table.content_id", '=', 'contents.id');         })         ->whereIn("$table.content_id",$ids)         ->update(array(                 "$table.expired" => 1,                 "$table.type" => "contents.type"         )); 

P.S: This is working when done on an sql editor:

UPDATE favorite_contents, contents SET favorite_contents.type = contents.type where favorite_contents.content_id = contents.id

like image 946
Bryan P Avatar asked Nov 21 '13 05:11

Bryan P


People also ask

What is DB :: Raw in laravel?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.

How do you update a record in laravel?

We can update the records using the DB facade with update method. The syntax of update method is as shown in the following table. Run an update statement against the database.

What is DB in laravel?

Laravel makes connecting with databases and running queries extremely simple. The database configuration file is app/config/database. php . In this file you may define all of your database connections, as well as specify which connection should be used by default.


1 Answers

code raw updates like this:

...->update( array(     'column' => DB::raw( 'column * 2' ) ) ); 
like image 101
AMIB Avatar answered Sep 22 '22 20:09

AMIB