【发布时间】:2015-11-15 09:57:27
【问题描述】:
当创建一个 eloquent 模型时:
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 时,他会解析我所有的 mutators:
public function getAddressnoAttribute()
{
return $this->attributes['fldNumRue'];
}
并在$this->attributes['fldNumRue'] 未定义时引发错误ErrorException: Undefined index... 所以我需要一种方法来使用它们的默认值初始化所有属性。
【问题讨论】:
标签: php laravel laravel-5 eloquent