55

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

Community
  • 1
  • 1
Bryan P
  • 4,142
  • 5
  • 41
  • 60

3 Answers3

111

code raw updates like this:

...->update( array(
    'column' => DB::raw( 'column * 2' )
) );
AMIB
  • 3,262
  • 3
  • 20
  • 20
79
DB::statement("UPDATE favorite_contents, contents SET favorite_contents.type = contents.type where favorite_contents.content_id = contents.id");

Try DB::statement for raw queries that does not involve outputting something (select).

Ironwind
  • 1,150
  • 11
  • 18
  • 3
    It's true that this is why his DB::raw() statement didn't execute anything. But the other answer that shows how to use DB::raw() within an update() is probably what most people viewing this question are probably looking for. – orrd Aug 28 '16 at 04:23
36

Will be work such similar, simple realization in Laravel 5.2 , Query Builder:

DB::table('stores')
            ->where('id', $request)
            ->update(['visibility' =>DB::raw($value)]);

This response is tested real site and working properly

Ivan Pirus
  • 1,026
  • 11
  • 21