Laravel eloquent 构造函数问题

Laravel eloquent issue with constructor

我有一个包含很多方法的模型。

class UserModel extends Eloquent{

    private $active;

    function __construct() {        
    $this->active = Config::get('app.ActiveFlag');
    }

    protected $table = 'User';
    protected $fillable = array('usr_ID', 'username');

    public function method1(){
      //use $active here
    }

    public function method2(){
      //use $active here
    }

}

控制器:

$user = new UserModel($inputall);
$user->save();

没有构造函数,它工作正常。但是,使用构造函数它不会保存用户(生成的查询没有任何填充属性或值)。查询如下:

 insert into User() values();

有什么意见吗?

嗯,是的,那是因为您覆盖了 Eloquent 构造函数,它负责在传递数组时用值填充模型。您必须使用 parent::__construct():

将它们传递给父级
public function __construct(array $attributes = array()){
    parent::__construct($attributes);
    $this->active = Config::get('app.ActiveFlag');
}

您模型的构造函数不接受任何参数 - 空 (),并且您正在控制器中创建 UserModel 的新实例,添加 $inputall 作为参数。

尝试根据此重构您的构造函数:

class UserModel extends Eloquent {
    public function __construct($attributes = array())  {
        parent::__construct($attributes);
        // Your additional code here
    }
}

(答案基于other Eloquent contructor question