小编Cas*_*per的帖子

将模型转换为数组或 JSON 时无法访问 Laravel 模型访问器

我正在开发 Laravel 项目,Laravel 版本是 5.4。在这个项目中,我使用一个名为 Agent 的模型,该模型带有访问器,将新属性附加到模型,如 Laravel文档中所述。

class Agent extends Model
{
   //return properties for sale count
   public function getPropertiesForSaleAttribute()
   {
        return 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以直接访问这个附加属性,

$agent::find(1)->properties_for_sale
//result = 1
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用 vue.js (json 响应)访问视图中的此属性时

agent.properties_for_sale
//result = null
Run Code Online (Sandbox Code Playgroud)

它返回 null 并且在 json 响应中看不到此属性。但是当我在模型中附加属性时,如下所示,

class Agent extends Model
    {
       protected $appends =[
          'properties_for_sale'
       ];

       //return properties for sale count
       public function getPropertiesForSaleAttribute()
       {
          return 1;
       }
    }
Run Code Online (Sandbox Code Playgroud)

我可以以相同的方式访问属性和 json 响应上可用的属性,

agent.properties_for_sale
//result = 1
Run Code Online (Sandbox Code Playgroud)

我无法理解 Laravel 的这种行为,为什么我需要附加属性来访问 json,因为在 …

php accessor laravel

2
推荐指数
1
解决办法
2081
查看次数

标签 统计

accessor ×1

laravel ×1

php ×1