【问题标题】:Test returns null for NOT NULL field with default value测试为具有默认值的 NOT NULL 字段返回 null
【发布时间】: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

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-11-19
      • 2013-12-08
      • 2013-01-29
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      相关资源
      最近更新 更多