Laravel 雄辩模型将所有值插入为 NULL


Laravel Eloquent Model inserts all values as NULL

我在使用Laravel Eloquent Model时遇到了问题

我有一个模型如下:

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();
     }
}

上面的代码应该可以正常工作,并且"活动"表中应该有一条记录。但是,当我运行此代码时,活动表列的所有值都作为 NULL 插入(auto_increment id 列除外)。

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

我的代码中是否有任何细微的错误?

不得将数据库字段定义为实际的类属性。问题是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 {

这是因为Eloquent使用魔法设置者/获取者。如果您这样做$model->randomAttribute那么它将查看数据的模型属性数组。

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

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

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

删除:

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');
}