gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:10:34 25 4
gpt4 key购买 nike

创建 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 时,他将解析我所有的修改器:

    public function getAddressnoAttribute()
{
return $this->attributes['fldNumRue'];
}

并引发错误,因为 $this->attributes['fldNumRue'] is not defined ErrorException: Undefined index... 所以我需要一种方法来初始化所有属性及其默认值。

最佳答案

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

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

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

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

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

关于php - 创建后 Laravel 5 Eloquent 加载模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32140596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com