iatstuti / laravel-nullable-fields
此特性允许您在将属性持久化到数据库时,轻松标记应设置为null的属性,使用Laravel PHP框架。
Requires
- php: ^8.1
- illuminate/contracts: ^10.0|^11.0
- illuminate/database: ^10.0|^11.0
- illuminate/events: ^10.0|^11.0
Requires (Dev)
- pestphp/pest: ^2.34
README
通常情况下,未分配值的数据库字段会默认为null
。当创建具有外键约束的记录且关系尚未建立时,这一点尤为重要。
public function up() { Schema::create('profile_user', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->nullable()->default(null); $table->foreign('user_id')->references('users')->on('id'); $table->string('twitter_profile')->nullable()->default(null); $table->string('facebook_profile')->nullable()->default(null); $table->string('linkedin_profile')->nullable()->default(null); $table->text('array_casted')->nullable()->default(null); $table->text('array_not_casted')->nullable()->default(null); }); }
MySQL的较新版本将如果字段未配置为允许null,则会将值转换为空字符串。请注意,较旧版本可能会实际返回错误。
Laravel目前不支持在将值分配给特定属性为空时自动将可空数据库字段设置为null
。
安装
此特性通过Composer安装。要安装,只需将其添加到您的composer.json
文件中。
$ composer require dyrynda/laravel-nullable-fields
为了使用此特性,在您的Eloquent模型中导入它,然后将受保护的$nullable
属性设置为要保存为null
的数组。
<?php use Illuminate\Database\Eloquent\Model; use Dyrynda\Database\Support\NullableFields; class UserProfile extends Model { use NullableFields; protected $nullable = [ 'facebook_profile', 'twitter_profile', 'linkedin_profile', 'array_casted', 'array_not_casted', ]; protected $casts = [ 'array_casted' => 'array', ]; }
现在,每次保存UserProfile
实例时,$nullable
属性中设置的任何空属性都将保存为null
。
<?php $profile = new UserProfile::find(1); $profile->facebook_profile = ' '; // Empty, saved as null $profile->twitter_profile = 'michaeldyrynda'; $profile->linkedin_profile = ''; // Empty, saved as null $profile->array_casted = []; // Empty, saved as null $profile->array_not_casted = []; // Empty, saved as null $profile->save();
如果您想将此行为扩展到模型上的所有字段,可以通过指定$nullable
为*
来实现。
class UserProfile extends Model { use NullableFields; protected $nullable = '*'; }
更多信息
在Eloquent模型中使用可空字段 - 第一版
在Eloquent模型中使用可空字段 - 第二版 - 第二版,涵盖了此包的细节
支持
如果您对此包有任何一般性问题,请随时在Twitter上联系我。
如果您认为您已发现一个问题,请使用GitHub问题跟踪器报告,或者更好的是,分支存储库并提交一个pull请求。
如果您正在使用此包,我很想听听您的想法。谢谢!
无价之宝
您可以使用此包,但如果它进入您的生产环境,您需要为世界买一棵树。
现在众所周知,解决气候危机并防止气温上升超过1.5C的最佳工具之一是植树。如果您支持此包并为其无价之宝森林做出贡献,您将为当地家庭创造就业机会并恢复野生动物栖息地。
您可以通过这里购买树木
更多关于无价之宝的信息请访问treeware.earth