【问题标题】:How to change the default boolean value in Laravel migration如何在 Laravel 迁移中更改默认布尔值
【发布时间】:2021-02-16 20:23:40
【问题描述】:

如何更改布尔值的默认值 例如,而不是 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);
    });
}

【问题讨论】:

    标签: laravel laravel-8


    【解决方案1】:

    数据库中布尔值的唯一可能值可以是 1/0 或真/假,如果您想从布尔值中获取自定义值,我建议您使用 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";
        }
    

    【讨论】:

      猜你喜欢
      • 2018-10-04
      • 2016-08-28
      • 2016-10-06
      • 2012-10-29
      • 2017-01-20
      • 2021-03-02
      • 2014-06-03
      • 2018-11-23
      • 2019-01-28
      相关资源
      最近更新 更多