【问题标题】:Laravel eloquent issue with constructor构造函数的 Laravel 雄辩问题
【发布时间】:2015-02-12 07:13:49
【问题描述】:

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

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();

请问有什么意见吗?

【问题讨论】:

    标签: php laravel constructor eloquent


    【解决方案1】:

    是的,这是因为你重写了 Eloquent 构造函数,该构造函数负责在传递数组时用值填充模型。您必须使用parent::__construct() 将它们传递给父级:

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

    【讨论】:

    • 非常感谢。完全错过了。
    【解决方案2】:

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

    尝试根据这个重构你的构造器:

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

    (根据other Eloquent contructor question回答)

    【讨论】:

      猜你喜欢
      • 2019-03-17
      • 2014-10-18
      • 2019-02-16
      • 2019-10-29
      • 1970-01-01
      • 2021-03-21
      • 2020-09-25
      • 2013-05-07
      相关资源
      最近更新 更多