测试为具有默认值的"非空"字段返回空值



>我有以下代码:我正在使用它来驱除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();
});
}

如果我在测试中保存后$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 AppModelsProperty;
use IlluminateDatabaseEloquentModel;
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 = 从数据库重新加载新的模型实例。 刷新 = 使用数据库中的新属性重新加载当前模型实例。

在这里找到了解决方案 - https://github.com/laravel/framework/issues/21449

最新更新