簡體   English   中英

Laravel:將 null 插入可為空的 boolean 列

[英]Laravel: insert null into boolean column that is nullable

所以我有一個 boolean 列,可以使用在 Laravel 中創建

$table->boolean('colName')->nullable();

我遇到的問題是我想在其中插入一個 null 值。

但據我所知,如果您將 null (使用 Eloquent 的創建或更新)分配,php 將評估 null 為 false,從而將 0(錯誤)分配到列中。

$toInsert = null;

這行不通。

我如何使用我的代碼

首先我從表單中獲取輸入

$nullableVal = $request->input('nullable-value');

if($nullableVal == "yes"){
    $toInsert = true;
}else if($nullableVal == "no"){
    $toInsert = false;
}else{
    $toInsert = null;
}

我的商店/更新通過 eloquent

$this->repository->update(['nullableVal' => $toInsert]);

有沒有解決的辦法?

謝謝

如果該字段可以為空,它的默認值應該是NULL ,對吧? 在這種情況下,只需刪除else情況。

$model = new Model;

if ($nullableVal == "yes") {
    $model->colName = true;
} elseif ($nullableVal == "no") {
    $model->colName = false;
}

$model->save();

如果$nullableVal既不是“是”也不是“否”,則不會設置 colName,因此在數據庫中變為 NULL。

如果遷移具有nullable() ,則默認情況下它在數據庫中已經是NULL

默認使$toInsert NULL

$nullableVal = $request->input('nullable-value');

$toInsert = NULL;

if($nullableVal == "yes"){
  $toInsert = true;
}

$this->repository->update(['nullableVal' => $toInsert]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM