【问题标题】:Laravel 5 eloquent load model properties after createLaravel 5 eloquent 加载模型属性后创建
【发布时间】:2015-11-15 09:57:27
【问题描述】:

当创建一个 eloquent 模型时:

Model::create(['prop1' => 1, 'prop2' => 2]);

返回的模型将只有 prop1prop2 作为属性,我可以做些什么来急切加载我没有插入数据库中的所有其他属性,因为它们是可选的?

编辑:我为什么需要这个?重命名我的数据库字段:

数据库

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-&gt;attributes['fldNumRue'] 未定义时引发错误ErrorException: Undefined index... 所以我需要一种方法来使用它们的默认值初始化所有属性。

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

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

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

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

    您可以通过覆盖模型中的 $attributes 属性并在那里设置默认值来做到这一点:

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

    【讨论】:

    • 效果很好,谢谢!但是是否有一种自动检索插入模型的“新”版本的方法?
    • 你可以用这个return parent::create(...)-&gt;refresh()覆盖模型(或基础模型)中的create方法,但这完全没有效率。
    • 你可以按照@Jan 的建议去做,但是想想你是否真的需要这个。这将导致为每个插入运行额外的选择查询
    • 我尽量避免使用数据库定义的默认值,并在 create() 签名中设置默认值。这样我就不需要重新获取对象
    猜你喜欢
    • 2014-06-17
    • 2013-06-18
    • 2015-01-26
    • 2015-03-12
    • 2019-07-17
    • 2017-09-13
    • 2017-09-02
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多