【问题标题】:Laravel eloquent updating tinyint (boolean)Laravel 雄辩地更新 tinyint(布尔值)
【发布时间】:2017-03-05 21:09:18
【问题描述】:

我在更新 eloquent 模型时遇到了一个奇怪的问题,我使用了一个复选框 (1 || undefined) 并在使用验证后修补了所有数据

$input = $request->all();
$service->update($input);

我试图专门检查复选框

$input['active'] = ($request->has('active') && $input['active']) ? 1 : 0

但它仍然不会影响数据库。

当我转储Request 时,我可以看到active: 10 但这些都不会改变update() 上的数据库

我做了一个快速测试和使用

$service->active = ($request->has('active') && $input['active']) ? 1 : 0 ;
$service->save();

完成了这项工作。但是为什么update() 没有更新这个字段呢?

【问题讨论】:

  • $input['active'] = $request->has('active') ? 1 : 0怎么样
  • 当您dd($request->input('active')) 时,它是否返回true
  • 另外,您在尝试此操作时是否遇到错误,或者它是否有效但只是不更新​​该字段?

标签: php laravel laravel-5 eloquent


【解决方案1】:

如果$request->active 返回true,但它仍然没有保存在数据库中,我敢打赌你忘了将active 添加到$fillable 数组中:

protected $fillable = ['something', 'something_else', 'active'];

https://laravel.com/docs/5.3/eloquent#mass-assignment

【讨论】:

  • 就是这样..我虽然我把它们都加了。
  • 谢谢!为我工作,但你能解释一下为什么会这样
  • @VinayKaithwas 你不能轻易地与 $fillable 数组中不存在的列进行交互。
【解决方案2】:

你试过了吗:

$input = $input->except(['active']);

$input['active'] = ($request->has('active') && $input['active']) ? 1 : 0;

$service->update($input);

希望这会有所帮助。

【讨论】:

  • 它也可以,但在 Laravel 中处理布尔值时更喜欢使用 truefalse(而不是 1 和 0)
猜你喜欢
  • 2020-05-30
  • 2020-02-14
  • 2017-04-28
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 2014-11-08
相关资源
最近更新 更多