创建 Eloquent 模型时:
返回的模型将仅具有
编辑:为什么需要这样做?重命名我的数据库字段。
数据库
问题在于当Laravel将所有内容转换为JSON时,它会解析所有的mutator:
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'];
}
}
问题在于当Laravel将所有内容转换为JSON时,它会解析所有的mutator:
public function getAddressnoAttribute()
{
return $this->attributes['fldNumRue'];
}
当$this->attributes['fldNumRue']
未定义时,会引发错误ErrorException: Undefined index...。因此,我需要一种方法来初始化所有属性及其默认值。
return parent::create(...)->refresh()
,但这样做会非常低效。 - Jan.J