bluecode/laravel-nullable-field

这个特性允许您轻松地将属性标记为应设置为null。

dev-master 2015-11-05 21:24 UTC

This package is not auto-updated.

Last update: 2024-09-18 18:13:23 UTC


README

通常,未赋值的数据库字段默认为null。在创建带有外键约束的记录时,这一点尤为重要。

注意,数据库字段必须配置为允许null。

MySQL的较新版本将在字段未配置为允许null时将值转换为空字符串。请注意,旧版本可能会返回错误。

Laravel (5.1) 目前不支持在分配给给定属性的值为空时自动将可空数据库字段设置为null

安装

此特性通过 Composer 安装。要安装,只需将其添加到您的 composer.json 文件中

{
	"require": {
		"bluecode/laravel-nullable-field": "~0.1"
	}
}

然后运行composer以更新您的依赖项

$ composer update

为了使用此特性,在您的Eloquent模型中导入它,然后将受保护的 $nullable 属性设置为包含您希望为空时保存为null的字段数组。

<?php

use Bluecode\Traits\NullableField;
use Illuminate\Database\Eloquent\Model;

class UserProfile extends Model
{
	use NullableField;
	
	protected $nullable = [
		'tel',
		'address'
	];
}

现在,每次您保存 UserProfile 配置实例时,在 $nullable 属性中设置的任何空属性都将保存为 null

<?php

$profile = new UserProfile::find(1);
$profile->tel = ' '; // Empty, saved as null
$profile->address  = '10 A Street';
$profile->save();

支持

如果您认为发现了问题,请使用 GitHub问题跟踪器 报告,或者更好的方法是fork存储库并提交pull请求。

如果您在使用此包,我很乐意听到您的想法。谢谢!