【问题标题】:Using laravel tinker and Carbon to mass update data使用 laravel tinker 和 Carbon 批量更新数据
【发布时间】:2021-02-08 00:43:59
【问题描述】:

我无法使用 tinker 和 Carbon 大规模更新数据,因为它不会遍历值

输入

>>> $d = Child::get('Birthday') //1st command

[!] Aliasing 'Child' to 'App\Child' for this Tinker session.
=> Illuminate\Database\Eloquent\Collection {#4195
     all: [
       App\Child {#4196
         Birthday: "2015-03-26",
       },
       App\Child {#4197
         Birthday: "2014-08-16",
       },
       App\Child {#4198
         Birthday: "2018-02-05",
       },
       App\Child {#4199
         Birthday: "1976-08-26",
       },
       App\Child {#4200
         Birthday: "1978-02-20",
       },
       App\Child {#4201
         Birthday: "2011-06-09",
       },
     ],
   }

>>> foreach($d as $ad) Child::query()->update(['Birthday' => Carbon\Carbon::parse($ad->Birthday)->format('Y:m:d')]) //2nd command

结果如下

Illuminate\Database\Eloquent\Collection {#4204
     all: [
       App\Child {#4205
         Birthday: "2011:06:09",
       },
       App\Child {#4206
         Birthday: "2011:06:09",
       },
       App\Child {#4207
         Birthday: "2011:06:09",
       },
       App\Child {#4208
         Birthday: "2011:06:09",
       },
       App\Child {#4209
         Birthday: "2011:06:09",
       },
       App\Child {#4210
         Birthday: "2011:06:09",
       },
     ],
   }

我只是想批量更新日期格式,但你可以看到它更新了所有错误

【问题讨论】:

  • 看起来它根据循环中的最后一个生日更新了所有记录。您应该使用$ad->update() 而不是Child::query()->update() - 因为目前您每次迭代都会更新所有记录。
  • @acvi 是这样的吗? foreach($d as $ad) $ad->update(['Birthday' => Carbon\Carbon::parse( $ad->Birthday)->format('Y:m:d')]) 不幸的是它什么也没做
  • 检查Birthday 是否在Child$fillable 属性中,然后它应该可以工作。

标签: laravel php-carbon tinker


【解决方案1】:

孩子::query()->update(['生日' => Carbon\Carbon::parse($ad->Birthday)->format('Y:m:d')]);

代码中的这一行会更新表中的每一行,因此在最后一轮 for each 循环中 此代码将每一行更新为最后一个生日。

因为它是一个字符串列,你可以像这样重新格式化它:

 $d = Child::get(['id','Birthday']);
foreach($d as $ad)
 Child::query()->where('id',$ad->id)->update(['Birthday' => Carbon\Carbon::parse($ad->Birthday)->format('Y:m:d')]);

here 有很多你可能喜欢的格式

但我必须说,这个列应该是日期列,而不是字符串

【讨论】:

  • 是的,结果很清楚,但我需要帮助或解决方案
  • 好的,你要做什么,你想改变db中生日列的格式吗?
  • 是的,生日列中的所有数据,提前致谢
  • 是字符串列吗?
  • PHP Parse error: Syntax error, unexpected ')', expecting ']' on line 1
猜你喜欢
  • 2014-11-25
  • 1970-01-01
  • 2017-12-01
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
相关资源
最近更新 更多