【问题标题】:Laravel - Modify Fetched Data With PaginationLaravel - 使用分页修改获取的数据
【发布时间】:2021-11-24 17:57:30
【问题描述】:

我想格式化从数据库中获取的某些列,但不知道如何。我使用 Laravel 8.x。这是sn-p:

车库控制器.php

$q = Garage::with('relative')->paginate(15);
return response()->json($q);

输出

{
  "data": [
    {
      "id": 39819,
      "name": "john",
      "date": "2020-12-20", // i want to format this with date_format()
      "relative": {
        "rid": 912039,
        "rname": "ROV" // and i just want this value instead of all columns
      }
    },
    {
      "id": 38178,
      "name": "danny",
      "date": "2020-12-20", // and this too
      "relative": {
        "rid": 182738,
        "rname": "YIV"
      }
    }
  ],
  "links": {
    .....
  },
  "meta": {
     ....
  }
}

模型,车库有属于相对的(相对的可以有多个车库)。

public function relative() {
   return $this->belongsTo(Relative::class, 'relative', 'rid');
}

我尝试了访问器,但它没有改变任何东西

public function getDateAttributes($value) {
  return date_format(date_create($value), 'd/m/Y');
}

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: php laravel eloquent laravel-8 laravel-pagination


    【解决方案1】:

    我认为您只需要从 getDateAttributes 中删除 s

    来自

    public function getDateAttributes($value) {
      return date_format(date_create($value), 'd/m/Y');
    }
    

    public function getDateAttribute($value) {
      return date_format(date_create($value), 'd/m/Y');
    }
    

    【讨论】:

    • 谢谢!上帝我想念那个。另外,如何将 relative 列修改为 "relative": "ROV" 而不是 "relative" : { "rid": 182738, "rname": "ROV"} ?我也应该使用访问器吗?
    • 是的,您可以修改它,但我更喜欢在该模式上添加虚拟列并在响应中返回此关系列。也请您批准我的回答并投票给我,这将鼓励我帮助更多的人。
    • 我尝试过投票,但我需要 15 个声望 ?。所以,就像,在 js 中,像这样访问它data[0].relative.rname ?
    • protected $appends = ['relativename']; 这样的模式中添加一个虚拟列,并且在该字段的访问器中,您需要返回值。或者按照下面的 URL 来帮助你。 stackoverflow.com/questions/67054990/…
    猜你喜欢
    • 2018-06-04
    • 2021-03-09
    • 2016-09-03
    • 1970-01-01
    • 2021-11-25
    • 2018-07-31
    • 2019-10-20
    • 2021-09-02
    • 2019-07-08
    相关资源
    最近更新 更多