簡體   English   中英

Laravel:如何檢查模型字段在數據庫上是否可以為空

[英]Laravel: How check if model field is nullable on database

保存時我將所有空字段設置為null

使用 OctoberCMS 模型事件beforeSave (相當於 Laravel 模型保存)

public function beforeSave()
{
    // $this => the model
    foreach ( $this->toArray() as $name => $value )
    {
         if ( empty( $value ) ) {
                 $this->{$name} = null;
         }
    }
}

問題是當字段在數據庫(mysql)上定義了默認值時,例如:

$table->integer('value')->default(1);

我需要獲取當前模型的所有可為空或不可為空的字段的數組。

這怎么辦?

Laravel/Eloquent對你的數據庫結構一無所知。 假設無論您實施什么操作,數據庫結構都已為它們准備就緒。

您可以查詢數據庫以獲取有關列的信息。 對於MySQL,您需要運行

show columns from <table_name>;

這將導致向數據庫發送額外的查詢

在我看來,更好的選擇是將此類信息存儲在模型類中,例如

protected $notNullable = ['field1', 'field2'];

以類似的方式存儲$fillable$guarded字段。 當您編寫模型時,您應該知道哪些列可以為nullable ,哪些不能為nullable ,因此它應該是最簡單的解決方案。

將此添加到您的模型或特征中

use DB;
...
    protected static $_columns_info = NULL;
    protected static $_nullable_fields = NULL;
    public function is_nullable(string $field_name){
        if (is_null(static::$_columns_info) ){
            static::$_columns_info = DB::select('show columns from '.$this->gettable() );
        }
        if (is_null(static::$_nullable_fields) ){
            static::$_nullable_fields = array_map( function ($fld){return $fld->Field;}, array_filter(static::$_columns_info,function($v){return $v->Null=='YES';}));
        }
        return in_array( $field_name, static::$_nullable_fields );
    }

並使用像

app(Model::class)->is_nullable(you_column_name)

暫無
暫無

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

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