首页 > 解决方案 > Laravel 5.4 - 模型访问器不起作用

问题描述

我一直试图让访问器工作几个小时,但无济于事。我已将我的模型代码简化为最基本的,但仍然没有运气。这是 PersonaIdentificacion.php 中的代码:`

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PersonaIdentificacion extends Modelo
{
    public $table = "personaidentificacion";

    public function getFooAttribute() {
        return 1;
    }

}`

我使用 Artisan Tinker 尝试检索“foo”属性的值,但我只得到:“null”。我不明白。我错过了什么??

标签: phplaravel

解决方案


你的 getFooAttribute() 很好。假设它是一个新属性,则在您的模型中添加以下内容

 protected $appends=['foo'];

然后你可以打电话

 $id = App\PersonaIdentificacion::first(); $id->foo;

这应该可以正常工作。


推荐阅读