加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – 创建后的Laravel 5 eloquent加载模型属性

发布时间:2020-12-14 19:44:22 所属栏目:大数据 来源:网络整理
导读:在创建雄辩的模型时: Model::create(['prop1' = 1,'prop2' = 2]); 返回的模型只有prop1 prop2作为属性,我可以做什么来急切加载我没有插入数据库的所有其他属性,因为它们是可选的? 编辑:为什么我需要这个?重命名我的数据库字段: 数据库 CREATE TABLE `tb
在创建雄辩的模型时:

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 AppModels;

/**
 * Class Customer
 * @package AppModels
 * @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->属性[‘fldNumRue’]未定义引发错误ErrorException:未定义索引…所以我需要一种方法来使用默认值初始化所有属性.

解决方法

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

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

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

你可以通过覆盖模型中的$attributes属性并在那里设置默认值来实现:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读