2013-11-21 39 views
12

這關係到我的質詢時指:怎麼辦更新查詢上laravel使用DB流利::原料

Update table1 field with table2 field value in join laravel fluent

但由於這是一種不同的方法,現在,我只想問另一個問題:

你如何正確使用做一個DB:raw更新?

我想用contents.type的值更新favorite_contents.type,但它什麼也沒做,靜態設置1到favorite_contents.expired正在工作。

這是我的代碼仍然不更新使用了DB::raw即使類型:

$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"); 

這之前,我使出那並不是上面的代碼不更新第一碼將不起作用以及:

$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" 
     )); 

PS: 這是一個SQL編輯器完成工作時:

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

回答

19
DB::statement("UPDATE favorite_contents, contents SET favorite_contents.type = contents.type where favorite_contents.content_id = contents.id"); 

嘗試DB::statement對於不涉及輸出內容(選擇)的原始查詢。

+1

的確,這就是爲什麼他的DB :: raw()語句沒有執行任何操作。但是另一個顯示如何在update()中使用DB :: raw()的答案可能是大多數查看此問題的人可能正在尋找的東西。 – orrd

28

代碼原材料更新這樣的:

...->update(array(
    'column' => DB::raw('column * 2') 
)); 
10

而且將工作這樣類似的,簡單的實現了在Laravel 5.2, 查詢生成器:

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

這種反應測試,真正的網站,可以正常使用