在批量更新中获取行ID

时间:2017-10-25 11:10:07

标签: php mysql laravel

我正在尝试优化下面提到的foreach循环

foreach($idsNoLongerInResponse as $offerId) {
  $offerId = $offerId->id;

  $offer = Offer::find($offerId);
  $offer->notes = "updated offer [offer_id=$offer->id]";

  $offer->save();
}

我已对此进行了优化,但我不确定在批量更新时如何获取每一行的ID。

 Offer::whereIn('id', $idsNoLongerInResponse)->update([
    'some_updates' => 1,

    // How can I get the row id here?
    'notes' => "updated offer [offer_id=$offer->id]"
]);

我走向错误的方向吗?任何帮助,将不胜感激。如果可能的话,请提供laravel eloquent和raw查询格式的解决方案。

1 个答案:

答案 0 :(得分:1)

您可以在更新中使用DB :: raw

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

检查讨论here

因此,按照您的示例,我认为您可以尝试此解决方案

Offer::whereIn('id', $idsNoLongerInResponse)->update([
    'some_updates' => 1,

    // How can I get the row id here?
    'notes' => DB::raw('CONCAT(CONCAT("updated offer [offer_id=", bot_offer_id), "]")')
]);