dongyan7172 2018-01-30 06:52
浏览 160
已采纳

是否可以向Laravel模型添加非持久属性?

I'm creating an API with Laravel (Lumen) in which there are objects which contain a field which is a path to a file.
These paths are stored as relative paths in the database but upon returning them to user I have to convert them to absolute urls.

Now I was wondering if there is a convenient way to add a non-persistent field to the model objects. Obviously there are Mutators but they are persisted to the database.

I also have thought of creating an after-middleware which traverses the object tree and converts every path field it finds but this is not an elegant way.

Here is the final transformation I need:

[
  {
    "id": 1,
    "title": "Some title",
    "media": [
      {
        "id": 435,
        "path": "relative/path/to/some/file.ext"
      },
      {
        "id": 436,
        "path": "relative/path/to/some/file2.ext"
      }
    ]
  }
]

To:

[
  {
    "id": 1,
    "title": "Some title",
    "media": [
      {
        "id": 435,
        "url": "http://example.com/relative/path/to/some/file.ext"
      },
      {
        "id": 436,
        "url": "http://example.com/relative/path/to/some/file2.ext"
      }
    ]
  }
]

Any idea is welcome.

  • 写回答

2条回答 默认 最新

  • douang4294 2018-01-30 06:56
    关注

    You can use Laravel accessors,

    From the Docs:

    The original value of the column is passed to the accessor, allowing you to manipulate and return the value.

    These are not persisted in the DB but are modified as and when you access them.

    For example:

    class User extends Model
    {
        /**
         * Get the user's first name.
         *
         * @param  string  $value
         * @return string
         */
        public function getFirstNameAttribute($value)
        {
            return ucfirst($value);
        }
    }
    

    Usage:

    $user = App\User::find(1);
    
    $firstName = $user->first_name;
    

    In your use case:

    Define an accessor in the Media Model for path attribute.

    public function getPathAttribute($value)
    {
        return storage_path($value);
    }
    

    If you need to access the property with a different name (alias):

    public function getAliasAttribute()
    {
        return storage_path($this->attributes['path']);
    }
    // $model->alias
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致