Php 创建后的Laravel 5雄辩负载模型属性
创建雄辩的模型时:Php 创建后的Laravel 5雄辩负载模型属性,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,创建雄辩的模型时: Model::create(['prop1' => 1, 'prop2' => 2]); 返回的模型将只有prop1和prop2作为属性,我可以做些什么来加载我没有插入到数据库中的所有其他属性,因为它们是可选的 编辑:我为什么需要这个?要重命名我的数据库字段,请执行以下操作: 数据库 CREATE TABLE `tblCustomer` ( `pkCustomerID` INT(11) NOT NULL AUTO_INCREMENT, `bacc
Model::create(['prop1' => 1, 'prop2' => 2]);
返回的模型将只有prop1
和prop2
作为属性,我可以做些什么来加载我没有插入到数据库中的所有其他属性,因为它们是可选的
编辑:我为什么需要这个?要重命名我的数据库字段,请执行以下操作:
数据库
CREATE TABLE `tblCustomer` (
`pkCustomerID` INT(11) NOT NULL AUTO_INCREMENT,
`baccount` VARCHAR(400) NULL DEFAULT NULL,
`fldName` VARCHAR(400) NULL DEFAULT NULL,
`fldNumRue` VARCHAR(10) NULL DEFAULT NULL,
....
PRIMARY KEY (`pkCustomerID`)
);
客户模型
<?php namespace App\Models;
/**
* Class Customer
* @package App\Models
* @property int code
* @property string name
* @property string addressno
*/
class Customer extends Model
{
protected $table = 'tblCustomer';
protected $primaryKey = 'pkCustomerID';
public $timestamps = false;
/**
* The model's attributes.
* This is needed as all `visible fields` are mutators, so on insert
* if a field is omitted, the mutator won't find it and raise an error.
* @var array
*/
protected $attributes = [
'baccount' => null,
'fldName' => null,
'fldNumRue' => null,
];
/**
* The accessors to append to the model's array form.
* @var array
*/
protected $appends = [
'id',
'code',
'name',
'addressno'
];
public function __construct(array $attributes = [])
{
// show ONLY mutators
$this->setVisible($this->appends);
parent::__construct($attributes);
}
public function setAddressnoAttribute($value)
{
$this->attributes['fldNumRue'] = $value;
return $this;
}
public function getAddressnoAttribute()
{
return $this->attributes['fldNumRue'];
}
}
并引发一个错误,因为$this->attributes['fldNumRue']
未定义错误异常:未定义索引。。。因此,我需要一种用默认值初始化所有属性的方法。您可以在模型上调用fresh()方法。它将从数据库中重新加载模型并返回它。请记住,它返回一个重新加载的对象-它不会更新现有的对象。还可以传递应重新加载的关系数组:
$model = $model->fresh($relations);
<>你可以考虑从数据库和模型中删除默认值。这样,您就不需要重新加载模型来获得默认值
您可以通过覆盖模型中的$attributes属性并在其中设置默认值来实现:
class MyModel extends Model {
protected $attributes = [
'key' => 'default value'
];
}
非常好,谢谢!但是,难道没有一种自动检索插入模型的“最新”版本的方法吗?您可以用这个
返回parent::create(…)->refresh()
,来覆盖模型(或基础模型)中的create方法,但这将是完全无效的。您可以按照@Jan的建议去做,但如果您真的需要的话,请考虑一下。这将导致为每个inserts运行额外的select查询这里还有另一种方法,我试图避免数据库定义的默认值,并在create()签名中设置默认值。这样我就不需要重新蚀刻对象
class MyModel extends Model {
protected $attributes = [
'key' => 'default value'
];
}