我正在开发 Laravel 项目,Laravel 版本是 5.4。在这个项目中,我使用一个名为 Agent 的模型,带有访问器将新属性附加到模型,如 Laravel documenation 中所述。 。
class Agent extends Model
{
//return properties for sale count
public function getPropertiesForSaleAttribute()
{
return 1;
}
}
我可以直接访问这个附加属性,
$agent::find(1)->properties_for_sale
//result = 1
但是,当我尝试使用 vue.js (json 响应)访问 View 中的此属性时
agent.properties_for_sale
//result = null
它返回null并且在json响应中看不到这个属性。但是当我在模型中附加属性时,如下所示,
class Agent extends Model
{
protected $appends =[
'properties_for_sale'
];
//return properties for sale count
public function getPropertiesForSaleAttribute()
{
return 1;
}
}
我可以以相同的方式访问属性,并且可以在 json 响应上访问属性,
agent.properties_for_sale
//result = 1
我无法理解 Laravel 的这种行为,为什么我需要附加属性来访问 json,因为在 Laravel 文档中他们没有提到这一点。
最佳答案
在@Namoshek的帮助下进行了多次挖掘后,这是我的答案。 properties_for_sale
属性最初并不存储在数据库中,这意味着 Eloquent 模型不为其保存值。当尝试检索属性的值时,Eloquent 将自动调用该访问器。因此我可以直接访问属性,如下所示,
$agent::find(1)->properties_for_sale
//result = 1
根据documentation将模型转换为数组或 JSON 时,需要添加数据库中没有相应列的属性。为此,首先需要定义该值的访问器。之后需要将属性名称添加到模型的appends属性中,如下所示,
class Agent extends Model
{
protected $appends =[
'properties_for_sale'
];
//return properties for sale count
public function getPropertiesForSaleAttribute() {
return 1;
}
}
将属性添加到附加列表后,它将包含在模型的数组和 JSON 表示形式中。
关于php - 将模型转换为数组或 JSON 时无法访问 Laravel 模型访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57798618/