如何在Laravel迁移中更改默认布尔值

时间:2020-11-04 06:13:29

标签: laravel laravel-8

如何更改布尔值的默认值 例如,我想将其更改为Yes/No

,而不是elibrary/evideo
public function up()
{
    Schema::create('elibrary', function (Blueprint $table) {
        $table->string('lm_ref_no',20)->comment('Learning Material No')->unique();
        $table->string('lm_desc',50)->comment('Learning Material Description');
        $table->boolean('section_posted')->comment('Section Posted')->default(true);
    });
}

1 个答案:

答案 0 :(得分:0)

如果要从布尔值中获取自定义值,则数据库中布尔值的唯一可能值为1/0或true / false,我建议您使用Mutators:https://laravel.com/docs/8.x/eloquent-mutators

它看起来像这样:

    public function getSectionPostedTransformedAttribute()
    {
        $result = "";

        if($this->section_posted == true) {
            $result = "elibrary";
        }

        if($this->section_posted == false) {
            $result = "evideo";
        }

        return $result;
    }
    
    //You can access the new value this way:
    $model->sectionPostedTransformed;

一种更清洁的方法:

    public function getSectionPostedTextAttribute()
    {
        return $this->section_posted ? "elibrary" : "evideo";
    }