thinkPHP5.x 更新字段为 NULL

简介

tp5.x 提供了丰富的数据模型和数据库操作的方法,只要涉及 thinkModel thinkQuery等,其中有一个软删除的 feature,可以指定字段$deleteTime来标记 record 是否删除。这个字段使用 NULL 来判断 record 有没有被标记。如果在标记为软删除下情况下,要恢复标记为删除的 record 就不能用 update save 了,因为如果你直接赋值 (PHP)null,这个字段就会被忽略, 不会对数据库的这个字段进行操作,SO fuck it.

其实在where方法中提供了操作为exp的形式

$user = new User;
$user->where('delete_time', 'exp', 'is not null')->field(true)-select();
#来选择没有被删除的 records

但是 update()save() 都是不支持 exp操作的,例如下面的操作都不可行

$ok = $user->where('id',$id)->update(['delete_time' => ['exp', 'NULL']]); # not working, returns 0
$ok = $user->where('id',$id)->update(['delete_time' => null]]); # omitted, returns 0
$ok = $user->where('id',$id)->update(['delete_time' => 'NULL']); # not working, returns 0

所有使用 thinkDb类来对数据表直接操作,而不是基于模型来操作。

use thinkDb;

# in Class
$ok = Db::table('ox_sliders') ->where('file_sha', $sha)->update(['delete_time' => ['exp','null'],]);
# now $ok is assigned to the number of rows that has been affected by this query.
# return 1, in my case

fuck it

  • tp版本为5.0.3
  • column 不能类型转换
  • ->data() 不能类型转换
  • ->save(),->update(),->data() 不支持 null 赋值

More

  • 如果你是新增数据,直接把 field 设置为default NULL
alert table table_name modify `delete_time` timestamp default null;
原文地址:https://www.cnblogs.com/raybiolee/p/6154719.html