我有一个扩展 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);
关于php - 在 Laravel Eloquent 中向表中插入一条空记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26863439/