php - 测试为具有默认值的 NOT NULL 字段返回 null
问题描述
我有以下代码:我正在使用它一种简单的方法来驱动 feature_set 表的列,因此希望 air_conditioning、pool .. 等具有默认为 0 的布尔值。
但是,当我使用工厂或像下面这样直接实例化它时->air_conditioning 始终为空,我不知道为什么。我使用 mysql Db 进行了测试,当我添加新行时,它默认为 0 正确。我在这里遗漏了什么,为什么没有在模型实例上设置默认值 0 。
class FeatureSetTest extends TestCase
{
use RefreshDatabase;
public function testCanCreateFeatureSetAndValuesDefaultToFalse()
{
$featureSet = new FeatureSet(['property_id' => '1']);
$featureSet->save();
$this->assertFalse($featureSet->air_conditioning);
}
}
...
public function up()
{
Schema::create('feature_sets', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('property_id');
$table->boolean('air_conditioning')->default(false);
$table->timestamps();
});
}
如果在测试中保存后我 dd $featureSet 我得到:
#attributes: array:4 [
"property_id" => "1"
"updated_at" => "2018-05-12 16:15:19"
"created_at" => "2018-05-12 16:15:19"
"id" => 1
]
如果我这样做 dd(DB::select(DB::raw('SHOW CREATE TABLE feature_sets'))); 它输出以下内容,因此将 0 设置为默认值,并且:
CREATE TABLE `feature_sets` (\n
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n
`property_id` int(10) unsigned NOT NULL,\n
`air_conditioning` tinyint(1) NOT NULL DEFAULT '0',\n
`created_at` timestamp NULL DEFAULT NULL,\n
`updated_at` timestamp NULL DEFAULT NULL,\n
PRIMARY KEY (`id`)\n
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_c
最后,如果我把 dd(DB::select(DB::raw('SELECT * FROM feature_sets'))); 在我的测试中,我可以看到默认值设置正确:
array:1 [
0 => {#598
+"id": 1
+"property_id": 1
+"air_conditioning": 0
+"created_at": "2018-05-12 15:44:31"
+"updated_at": "2018-05-12 15:44:31"
}
]
//特征集模型。
<?php
namespace App\Models\Property;
use Illuminate\Database\Eloquent\Model;
class FeatureSet extends Model
{
protected $guarded = [];
public function asFeaturesArray()
{
return [
'air_conditioning' => [
'title' => __('Air Conditioning'),
'value' => $this->air_conditioning
]
];
}
}
我不明白为什么它不给我 0 回报 ->air_conditioning
解决方案
原来这$featureSet->refresh()
就是这个问题的答案,->fresh()
上面只是获取模型具有的现有属性的新值,其中刷新获取所有属性的新版本 - 其中包括我默认为 0 的属性。
fresh = 从数据库重新加载一个新的模型实例。refresh = 使用数据库中的新属性重新加载当前模型实例。
在这里找到了解决方案 - https://github.com/laravel/framework/issues/21449
推荐阅读
- c# - EmguCV 斑点计数器
- python - python可以在mac上打开一个应用程序并执行一个动作吗?
- java - 使用 Guice 注入对 JAX-RS/Jersey servlet 进行单元测试
- wordpress-gutenberg - 古腾堡的 TinyMCE getContent 和 setContent 函数有哪些替代方案?
- php - 组查询月
- buddypress - 如何获取当前用户的 buddypress 字段?
- c - 导入模块 - C 中的自定义模块
- css - 使用 CSS 隐藏 div 中的锚标记之间的逗号
- laravel-5 - 分块返回 laravel 查询结果
- java - 如何解析文本文件以使用 java 在另一个文本文件中写入某些行?