thinkPHP5.x 更新字段為 NULL


簡介

tp5.x 提供了豐富的數據模型和數據庫操作的方法,只要涉及 think\Model think\Query等,其中有一個軟刪除的 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

所有使用 think\Db類來對數據表直接操作,而不是基於模型來操作。

use think\Db;

# 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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM