首页 > 解决方案 > 测试为具有默认值的 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

标签: phplaravellaravel-5

解决方案


原来这$featureSet->refresh()就是这个问题的答案,->fresh()上面只是获取模型具有的现有属性的新值,其中刷新获取所有属性的新版本 - 其中包括我默认为 0 的属性。

fresh = 从数据库重新加载一个新的模型实例。refresh = 使用数据库中的新属性重新加载当前模型实例。

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


推荐阅读