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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?