代码之家  ›  专栏  ›  技术社区  ›  Cengkuru Michael

在laravel雄辩的结果中添加额外的关键点

  •  2
  • Cengkuru Michael  · 技术社区  · 8 年前

    {
      "data": [
        {
          "id": "",
          "awardID": 2,
          "title": "Dummy title",
          "status": "active",
          "raceStart":"",
          "raceEnd:":""
        }
      ]
    }      
    

    {
      "data": [
        {
          "id": "",
          "awardID": 2,
          "title": "Dummy title",
          "status": "active",
          "period": {
            "raceStart":"",
            "raceEnd:":""
          }
        }
      ]
    } 
    

    如果周期是一个与父表具有1:1关系的表,那么这会容易得多,但这里不是这样。 如何实现这一点?

    1 回复  |  直到 8 年前
        1
  •  4
  •   Priya Sajeetharan    8 年前

    检查这是否有效。虽然我没有尝试过,但根据文档,我们可以添加访问器和变异器。但它会改变你对模型的每一个反应。

    // Your Model
    class Race extends Model
    {
        {...}
        protected $appends = ['period'];
        // accessor
        public function getPeriodAttribute($value)
        {  
            $this->attributes['period'] = (object)[];
            $this->attributes['period']['raceStart'] = $this->attributes['raceStart'];
            $this->attributes['period']['raceEnd'] = $this->attributes['raceEnd'];
            unset($this->attributes['raceStart']); = $value;
            unset($this->attributes['raceEnd']);
            return $this->attributes['period'];
        }
    }
    

    $race->period 将给出 raceStart raceEnd 价值

    https://laravel.com/docs/5.4/eloquent-mutators#accessors-and-mutators

    否则,另一个选项是在查询后,执行 map

    {...}
    ->map(function($data) {
        $data->period = (object)[];
        $data->period['raceStart'] = $data->raceStart;
        $data->period['raceEnd'] = $data->raceEnd;
        unset($data->raceStart);
        unset($data->raceEnd);
        return $data;
    });
    

    https://laravel.com/docs/5.4/eloquent-collections#introduction

    使用QueryBuilder

    $races = DB::table('races')->get();
    
    $races = array_map(function ($data) {
        $data->period = (object)[
            "raceStart" => $data->raceStart,
            "raceEnd" => $data->raceEnd
        ];
        unset($data->raceStart);
        unset($data->raceEnd);
        return $data;
    }, $races->data);