2

我有这个关系:

每个用户都有画廊,画廊有很多文件。

两个用户可以拥有同一日期的画廊。

这是输出 JSON 响应:

User1 {
 galleries: {
  created_at: 23.04.2019.
  files: [
    {
     path: "path/to/file.jpg"
    },
    {
     path: "path/to/file2.jpg"
    },
  ]
 }
},
User2 {
 galleries: {
  created_at: 23.04.2019.
  files: [
    {
     path: "path/to/file3.jpg"
    },
    {
     path: "path/to/file4.jpg"
    },
  ]
 }
}

我需要以某种方式按 created_at 值对画廊进行分组,但是为了分组画廊对象,将所有文件保留在相同的 JSON 响应中。像这样:

Users {
 galleries: {
  created_at: 23.04.2019.
  files: [
    {
     path: "path/to/file.jpg"
    },
    {
     path: "path/to/file2.jpg"
    },
    {
     path: "path/to/file3.jpg"
    },
    {
     path: "path/to/file4.jpg"
    },
  ]
 }
},

我尝试使用->groupBy('galleries.created_at'),但我得到了这个 - 第一个画廊的第一个文件,第二个画廊的第一个文件

Users {
 galleries: {
  created_at: 23.04.2019.
  files: [
    {
     path: "path/to/file.jpg"
    },
    {
     path: "path/to/file3.jpg"
    },
  ]
 }
},
4

1 回答 1

0

在将数据传递到 Fractal Transformer 之前,需要获取正确的数据。您想要的输出看起来是按日期File组织的 s列表。Gallery它实际上没有任何关系Users(除非您计划稍后确定返回数据的范围)。话虽如此,Eloquent 关系在这里并没有真正的帮助,因为我们不处理单个模型的关系,我们可以只使用 Laravel 查询构建器并使用groupByCollection 辅助函数来组织结果。

这取决于你把这个方法放在哪里;它可以很容易地进入控制器方法,但如果您计划确定结果的范围(例如,到某些Users 或某些日期,如下所示),您可能会在模型中使用它。

// Gallery.php

public static function filesByGalleryDate($date = null) {
    $query = DB::table('gallery')
        ->leftJoin('files', 'galleries.id', '=', 'files.gallery_id')
        ->select('galleries.created_at', 'files.*')
        ->orderBy('galleries.created_at');

    $result = $date == null 
        ? $query->get()
        : $query->where('galleries.created_at', $date)->get();

    return $result->groupBy('created_at')

        // for each date, convert inner stdClasses to arrays
        ->map(function($date) { 
            return $date->map(function($file) { 
                return (array) $file; 
            }); 
        });
}
于 2020-02-10T04:33:57.423 回答