【发布时间】:2018-10-22 19:50:24
【问题描述】:
我有以下代码:我正在使用它一种简单的方法来驱动 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
【问题讨论】: