【问题标题】:Laravel: How check if model field is nullable on databaseLaravel:如何检查模型字段在数据库上是否可以为空
【发布时间】:2020-01-24 16:22:04
【问题描述】:

保存时我将所有空字段设置为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);

我需要获取当前模型的所有可空或不可空字段的数组。

这是怎么做到的?

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    Laravel/Eloquent 不知道你的数据库的结构。假设无论您实现什么操作,数据库结构都已为它们准备好。

    您可以查询数据库以获取有关列的信息。对于 MySQL,您需要运行

    show columns from <table_name>;
    

    这将导致向数据库发送其他查询

    在我看来,更好的选择是将此类信息存储在模型类中,例如在

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

    以类似的方式存储 $fillable$guarded 字段。当您编写模型时,您应该知道哪些列是nullable,哪些不是,因此它应该是最简单的解决方案。

    【讨论】:

    • 亲爱的投票者,请发表评论,我很想知道答案有什么问题:)
    • 抱歉。要解决我只需设置protected $notNullables = ['foo', 'bar'] 并在循环内创建条件。工作正常。
    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-03
      • 2014-11-06
      • 2018-09-16
      • 2015-06-19
      • 2022-09-23
      • 2015-02-22
      • 1970-01-01
      • 2022-11-12
      相关资源
      最近更新 更多