temper / laravel-nullable-properties
此包已被废弃且不再维护。未建议替代包。
1.0.1
2021-03-22 10:31 UTC
Requires
- php: >=7.0
Requires (Dev)
- orchestra/testbench: ^6.12
- phpunit/phpunit: *
README
此包为Eloquent模型提供自动空值属性。
当修复Eloquent模型时,可能常见的情况是这样做
$this->property = $request->get('property');
或者甚至
$this->fill($request->all());
这种做法的副作用是,表单中的空字段在数据库中以空字符串的形式存储,即使数据库列是可空的。
这可能会干扰未来的查询,例如
$users = User::whereNull('favoriteColor')->get();
用法
用法简单。添加
NullableProperties
特性- 一个名为
$nullable
的数组,包含模型属性名(类似于$fillable
和$casts
) 的数组
<?php use Illuminate\Database\Eloquent\Model; use Temper\NullableProperties\NullableProperties; class User extends Model { use NullableProperties; public $nullable = ['favoriteColor']; };
此数组中的属性不允许以空字符串的形式存储,当为空时,总是默认回退到 null
。
Laravel 在运行时难以轻松检测可空值。但你可以轻松地从数据库中获取一个表的可空属性
select concat('protected $nullable = [', group_concat(concat("'",column_name,"'")),'];') from information_schema.columns where table_name = 'users' and is_nullable = 'YES' and data_type = 'varchar';