dyrynda / 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请求。
如果您在使用此包,我非常想听听您的想法。谢谢!
Treeware
您可以使用此包,但如果它进入您的生产环境,您需要为世界买一棵树。
现在众所周知,解决气候危机并防止我们的温度上升到1.5C以上的最佳工具之一是植树。如果您支持这个包并为Treeware森林做出贡献,您将为当地家庭创造就业并恢复野生动物栖息地。
您可以通过这里购买树木。
在treeware.earth上了解更多关于Treeware的信息