将属性传递给Eloquent模型构造函数

时间:2014-10-25 07:24:21

标签: laravel eloquent

也许我做错了,但是我来自PDO的世界,我习惯于将参数传递给一个实例化了一行的类,然后该构造函数将动态设置一个字段为了我。如何通过Eloquent实现这一目标?

// Old way

$dm = new DataModel('value');

DataModel.php

class DataModel() {
   function __construct($value = null) {
      $this->value = $value;
   }
}

我读过Eloquent为您提供::create()方法,但我不想在此阶段保存记录。

这里的问题是Eloquent有自己的构造函数,我不确定我的模型是否可以完全覆盖该构造函数。

3 个答案:

答案 0 :(得分:11)

您可以添加到您的模型中:

public function __construct($value = null, array $attributes = array())
{
    $this->value = $value;

    parent::__construct($attributes);
}

这将执行您想要的操作并启动父构造函数。

答案 1 :(得分:5)

我相信你正在寻找Laravel所谓的Mass Assignment

您只需定义一个可填充属性数组,然后在创建新对象时就可以传入这些属性。无需覆盖构造函数!

class DataModel extends Eloquent {
    protected $fillable = array('value');
}

$dataModel = new DataModel(array(
    'value' => 'test'
));

有关更多信息,请查看official docs

答案 2 :(得分:0)

旧构造函数格式:

 protected $value;
 public function __construct( $value = null)
    {

         $this->value = $value;

    }

新格式:

protected $value;    
public function __construct(array $attributes = array(), $value =null)
{
    /* override your model constructor */
    parent::__construct($attributes);

    $this->value = $value;
}