doubo6658 2015-01-31 11:24
浏览 334
已采纳

Laravel Eloquent Model将所有值都插入为NULL

I have run into problems with Laravel Eloquent Model

I have a model as follow:

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

    protected $timestamps = false;

    public $item;

    public $content;

    public $year;

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

And the corresponding controller:

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

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

         $activity->save();
     }
}

The above code should work fine and there should be a record in 'activity' table. However, all the value of columns of activity table are inserted as NULL when I run this code (except for the id column which is auto_increment).

In addition, when I var_dump the $activity (just before calling $activity->save()), the $activity with all of its properties are shown as expected (I mean, with values I've assigned before)

Is there any subtle error in my code?

  • 写回答

3条回答 默认 最新

  • dongwang6837 2015-01-31 11:32
    关注

    You must not define database fields as actual class properties. The problem is that Laravel uses an $attributes array internally, not the models properties.

    When doing

    $activity->content = 'Example content';
    

    Laravel uses the magic __set() method to update the value in it's $attributes array. But that setter method is never called because you have an actual property with that name.

    What you need to do to resolve this problem is remove the properties:

    class Activity extends Eloquent {
        protected $table = 'activity';
    
        protected $timestamps = false;
    
        protected $fillable = array('item', 'content', 'year');
    }
    

    If you want to document the properties and have autocomplete support you can use the @property annotation:

    /**
     * @property string $item
     * @property string $content
     * @property int $year
     */
    class Activity extends Eloquent {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题