douchuza8908 2018-10-03 12:09
浏览 169
已采纳

检索模型时添加自定义属性

Is possible to attach a custom attribute when retrieving a model in laravel?.

The problem is that I need to return some data that is not in the database along the info from the database. I've been doing it manually but I guess that there might be a way to do it in the model.

Example: I have an application table. Each application contains a folder with documents with the same application id. I need to attach the amount of files the folder that correspond to each application.

This is what I do:

$application = Application::get();
$application = $application->map(function($a){
    $a->files = $this->getFiles($a->id); // This gets the amount of files
    return $a;
})

Is there some way to do it in the model in a way that $application->files is already contained in $application when doing Application::get()

  • 写回答

2条回答 默认 最新

  • dsdf64562672 2018-10-03 12:14
    关注
    class User extends Model
    {
        public function getFooBarAttribute()
        {
            return "foobar";
        }
    }
    

    And access to that attribute like:

    $user->foo_bar;
    

    or like,

    $user->fooBar;
    

    More detailed documentation; https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)