在Laravel中,Eloquent在表中插入了一条空记录


In Laravel Eloquent inserts an empty record to table

我有一个扩展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的新记录,但所有其他字段都是空字符串或零。这怎么可能?

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

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

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

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

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

// 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";
    });
}