laravel 将属性传递给 Eloquent 模型构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26560207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing an attribute to Eloquent model constructor
提问by silkfire
Maybe I'm doing things wrong, but I'm coming from the world of PDO and I'm used to be able to pass arguments to a class that a row is instantiated into and then that constructor will set a field dynamically for me. How is this achieved with Eloquent?
也许我做错了,但我来自 PDO 的世界,我习惯于将参数传递给一个类,一个行被实例化到,然后该构造函数将为我动态设置一个字段。Eloquent 是如何做到这一点的?
// Old way
$dm = new DataModel('value');
DataModel.php
数据模型.php
class DataModel() {
function __construct($value = null) {
$this->value = $value;
}
}
I've read that Eloquent provides you with a ::create()
method but I don't want to save the record at this stage.
我读过 Eloquent 为您提供了一种::create()
方法,但我不想在此阶段保存记录。
The issue here is that Eloquent has its own constructor and I'm not sure my model can override that constructor completely.
这里的问题是 Eloquent 有自己的构造函数,我不确定我的模型是否可以完全覆盖该构造函数。
回答by Marcin Nabia?ek
You can add to your model:
您可以添加到您的模型:
public function __construct($value = null, array $attributes = array())
{
$this->value = $value;
parent::__construct($attributes);
}
this will do what you want and launch parent constructor.
这将执行您想要的操作并启动父构造函数。
回答by lukasgeiter
I believe you are looking for a thing Laravel calls Mass Assignment
我相信你正在寻找 Laravel 称之为 Mass Assignment 的东西
You simply define an array of fillable properties, which you are then able to pass in, when creating a new object. No need to override the constructor!
您只需定义一组可填充的属性,然后您就可以在创建新对象时将其传入。无需覆盖构造函数!
class DataModel extends Eloquent {
protected $fillable = array('value');
}
$dataModel = new DataModel(array(
'value' => 'test'
));
For more Information take a look at the official docs
有关更多信息,请查看官方文档
回答by Amine_Dev
old constructor format :
旧的构造函数格式:
protected $value;
public function __construct( $value = null)
{
$this->value = $value;
}
new format :
新格式:
protected $value;
public function __construct(array $attributes = array(), $value =null)
{
/* override your model constructor */
parent::__construct($attributes);
$this->value = $value;
}