【问题标题】:In Laravel Eloquent inserts an empty record to table在 Laravel Eloquent 中,向表中插入一条空记录
【发布时间】:2014-11-11 11:07:50
【问题描述】:

我有扩展 Eloquent 的 Word 类。我手动添加了两条记录,它们使用Word::all() 方法可以很好地获取。但是当我尝试创建新对象并保存它时,Eloquent 会在表中插入空值。

所以,这是模型

class Word extends Eloquent {
    protected $table = 'words';
    public $timestamps = false;

    public $word;
    public $senseRank = 1;
    public $partOfSpeech = "other";
    public $language;
    public $prefix;
    public $postfix;
    public $transcription;
    public $isPublic = true;
}

这是数据库迁移脚本

     Schema::create('words', function($table) {
         $table->increments('id');
         $table->string('word', 50);
         $table->tinyInteger('senseRank');
         $table->string('partOfSpeech', 10);
         $table->string('language', 5);
         $table->string('prefix', 20)->nullable();
         $table->string('postfix', 20)->nullable();
         $table->string('transcription', 70)->nullable();
         $table->boolean('isPublic');
     });

这是我要运行的代码

Route::get('create', function()
{
    $n = new Word;
    $n->word         = "hello";
    $n->language     = "en";
    $n->senseRank    = 1;
    $n->partOfSpeech = "other";
    $n->save();
});

我得到的只是一个具有正确新 ID 的新记录,但所有其他字段都是空字符串或零。怎么可能?

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    您需要从模型中删除所有属性,因为现在 Eloquent 无法正常工作,您的类应该如下所示:

    class Word extends Eloquent {
        protected $table = 'words';
        public $timestamps = false;
    }
    

    如果您需要某些字段的默认值,您可以在使用default 创建表时添加它们,例如:

    $table->tinyInteger('senseRank')->default(1);
    

    【讨论】:

      【解决方案2】:

      注释掉/去掉你正在设置的类字段:

      // public $word;
      // public $senseRank = 1;
      // public $partOfSpeech = "other";
      // public $language;
      

      Laravel 使用魔术 __get()__set() 方法在内部存储字段。当您定义了字段时,这不起作用。

      您可以使用模型事件来设置默认值,将此方法添加到您的模型中:

      public static function boot() {
          parent::boot();
          static::creating(function($object) {
              $object->senseRank = 1;
              $object->partOfSpeech = "other";
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-12
        • 2016-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        相关资源
        最近更新 更多