doubo6658 2015-01-31 03:24
浏览 335
已采纳

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 03: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部