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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!