Laravel Eloquent 模型将所有值插入为 NULL

Laravel Eloquent Model inserts all values as NULL

我 运行 遇到 Laravel Eloquent 模型

的问题

我有一个模型如下:

class Activity extends Eloquent {
    protected $table = 'activity';

    protected $timestamps = false;

    public $item;

    public $content;

    public $year;

    protected $fillable = array('item', 'content', 'year');
}

以及对应的控制器:

class ActivityController extends \BaseController {
     public function create()
     {
         $activity = new Activity();

         $actitity->item = 'Example';
         $activity->content = 'Example content';
         $activity->year = 2015;

         $activity->save();
     }
}

上面的代码应该可以正常工作并且 'activity' table 中应该有一条记录。但是,当我 运行 这段代码时,activity table 的所有列的值都被插入为 NULL(除了 id 列是 auto_increment)。

此外,当我 var_dump $activity(就在调用 $activity->save() 之前)时,$activity 及其所有属性按预期显示(我的意思是,使用我之前分配的值)

我的代码有什么细微的错误吗?

这是因为Eloquent使用魔法setters/getters。如果你这样做 $model->randomAttribute 那么它会查看数据的模型属性数组。

因为您已经明确定义了每个属性,所以它直接访问 属性 而不是魔法 getter。当您调用save()时,该函数将所有数据保存在不包含任何内容的属性数组中。

删除属性定义,它将起作用。

如果您调用 $model->getAttributes(),您将看到其中不包含任何数据。

您不得将数据库字段定义为实际的 class 属性。问题是 Laravel 在内部使用了一个 $attributes 数组,而不是模型属性。

做的时候

$activity->content = 'Example content';

Laravel 使用神奇的 __set() 方法更新其 $attributes 数组中的值。但是那个 setter 方法永远不会被调用,因为你有一个实际的 属性 用那个名字。

要解决此问题,您需要做的是删除属性:

class Activity extends Eloquent {
    protected $table = 'activity';

    protected $timestamps = false;

    protected $fillable = array('item', 'content', 'year');
}

如果您想记录属性并获得自动完成支持,您可以使用 @property 注释:

/**
 * @property string $item
 * @property string $content
 * @property int $year
 */
class Activity extends Eloquent {

删除:

public $item;

public $content;

public $year;

来自:

class Activity extends Eloquent {
    protected $table = 'activity';

    protected $timestamps = false;

    public $item;

    public $content;

    public $year;

    protected $fillable = array('item', 'content', 'year');
}