Laravel 5 Eloquent创建后加载模型属性

6
创建 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时,它会解析所有的mutator:
    public function getAddressnoAttribute()
    {
        return $this->attributes['fldNumRue'];
    }

$this->attributes['fldNumRue']未定义时,会引发错误ErrorException: Undefined index...。因此,我需要一种方法来初始化所有属性及其默认值。

1个回答

8

您可以在您的模型上调用fresh()方法,它将重新从数据库中加载模型并将其返回。请注意它返回一个重新加载的对象 - 它不会更新现有的对象。您还可以传递应被重新加载的关联数组:

$model = $model->fresh($relations);

您可以考虑从数据库和模型中删除默认值,这样您就不需要重新加载模型以获取默认值了。

您可以通过重写模型中的$attributes属性并在其中设置默认值来实现:

class MyModel extends Model {
  protected $attributes = [
    'key' => 'default value'
  ];
}

非常好,谢谢!但是难道没有自动获取插入模型的“新鲜”版本的方法吗? - kitensei
你可以通过在模型(或基础模型)中重写create方法来使用return parent::create(...)->refresh(),但这样做会非常低效。 - Jan.J
我尽量避免使用数据库定义的默认值,并在create()签名中设置默认值。这样我就不需要重新获取对象了。 - jedrzej.kurylo
我不太明白,请问可以在某个地方发布一个示例吗? - jedrzej.kurylo
我明白了。如果您的数据库字段名称与模型中的不同,则需要为它们编写getter方法。在$attributes中使用数据库字段名称 - 它们需要作为属性数组存在,以便稍后用于构建插入查询,并且字段名称必须匹配。 - jedrzej.kurylo
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接