php - 在 Laravel Eloquent 中向表中插入一条空记录

标签 php laravel laravel-4 eloquent

我有一个扩展 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/

相关文章:

php - Laravel 5.3 尝试为真但 Auth::User 返回 null?

php - Laravel 的新手,想知道我是否正确使用模型

laravel - 多对多和急切加载查询

laravel-4 - Laravel 4 - 无法覆盖 getDateFormat()

laravel 4 - 理解模型和数据库表关系

php - Symfony2 - 显示动态可选角色

php - 全局变量如何在 php 中工作?

php - PostgreSql 所有返回结果都是 "Array"

php - 在 Laravel 5 中按行排序并限制结果

php - App\Http\Controllers\Admin\SettingsController::destroy() 缺少参数 1