使用Laravel更新数据库中的所有记录

时间:2018-04-03 20:34:25

标签: php laravel

我有这个:

$keys = Keys_Info::all();

foreach ($keys as $key)
{
          $rank = 1; //Example.. In real it's variable..
          DB::table('keys_info')
                      ->where('id', $key->id)
                      ->update(['rank' => $rank]);
}

这只会更新第一行,而不是全部。如何让它更新所有行?

修改

foreach($keys as $key)
{
   print $key->id; //Example printing all keys
   foreach($results as $results)
   {
            print $key->id; //Example printing all keys

            if (in_array($key->example, $array))
            {
               print $key->id; //Example printing first row key!
               $rank = 1; //Example
               DB::table('keywords_info')
                           ->where('id', $key->id)
                           ->update(['url_rank' => $rank]);
            }
   }
}

起初我没有解释清楚,这是我使用的完整代码。我发现它在IF语句中不起作用

1 个答案:

答案 0 :(得分:1)

当您更新所有行时,您可以像下面这样做

 DB::table('keys_info')->update(['rank' => $rank]);

如果您仍想传递ID,可以执行以下操作

//Fetch all ids in array
$keys=Keys_Info::pluck('id')  OR Keys_Info::value('id')
//apply in query
DB::table('keys_info')->whereIn('id', $keys)->update(['rank' => $rank]);