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

Php 在Laravel中,Eloquent向表中插入一条空记录,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,我有一个扩展了雄辩的类Word。我手动添加了两条记录,使用Word::all()方法可以很好地获取它们。但当我试图创建新对象并保存它时,Eloquent会将空值插入表中 这是模型 class Word extends Eloquent { protected $table = 'words'; public $timestamps = false; public $word; public $senseRank = 1; public $partOfSp

我有一个扩展了雄辩的类
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使用magic
\uuu get()
\uu set()
方法在内部存储字段。如果定义了字段,则此操作不起作用

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

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