【问题标题】:Addition of a new value to API response向 API 响应添加新值
【发布时间】:2021-06-23 02:43:31
【问题描述】:

目前正在学习 Laravel,非常感谢任何帮助! 我的 API 控制器具有以下 index 函数

public function index()
{
    abort_if(Gate::denies('course_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');

    $response=Course::all()->toArray();
    
    $allData = [];
    foreach (Course::all() as $ids=>$CMF) {
        
        UNSET($response[$ids]['media']);

        $data_sequence = DB::table('media_sequence')->where('data_id', $CMF["id"])->where('type','CMF')->first();

        $data_id=$data_sequence->id;
        $data_sequence = json_decode($data_sequence->data_sequence);
        $data = [];
        $data["id"] = $CMF["id"];
        $data["title"] = $CMF["title"];
            
        foreach ($data_sequence as $id => $dataSeq) {
            if ($dataSeq->type == "Text") {
                $response[$ids]['media'][]=["id"=>$data_id,"text"=> $dataSeq->name,"mime_type"=>"text"];
            } elseif ($dataSeq->type == "file") {
                foreach ($CMF["media"] as $file) {
                    if (str::slug($dataSeq->name) == str::slug($file["file_name"])) {
                        $file["thumb"] = $file->getUrl('video_thumb');
                        $response[$ids]['media'][]=$file;
                    }
                }
            }
        }
        $allData[] = $data;
    }
    return new CourseResource($response);

    //Commented: return new CourseResource(Course::with(['category', 'assigned_teams', 'team'])->get());
}

尝试用$response 返回'assigned_teams' 时没有结果 API 响应仍然不包含'assigned_teams'

我试过了:return new CourseResource($response, 'assigned_teams');

【问题讨论】:

  • 我不确定我是否理解这里的问题,但我想指出这段代码看起来有点乱。 (a) 您正在执行Course::all() 两次,这将两次访问数据库以获得完全相同的数据 (b) 您遇到 N+1 问题,因为您正在为检索到的每个模型进行数据库查询。您可能想查看laravel.com/docs/8.x/eloquent-relationships,了解如何在 Courses 上定义关系并立即加载您需要的所有相关模型。另请查看 laravel.com/docs/8.x/eloquent-resources 将响应映射到特定表单
  • 您也可以使用array castdata_sequence 转换为数组,而无需手动执行,但这需要您为media_sequence 的行创建一个Eloquent 模型
  • media_sequence 返回数据正常,我只需要返回 'assigned_teams' 和 $response。我认为它的一行修改仅在 return new CourseResource($response);
  • 尝试使用Course::with('assigned_teams')->all() 而不是Course::all()(在这两个地方...)
  • 根据您的代码,我假设assigned_teams 是一种关系。由于该行已被注释,因此它不包含在响应数组中。

标签: php laravel api


【解决方案1】:

它没有返回 assigned_items,因为它不包含在 $response 数组中。

改变

$response=Course::all()->toArray();

$response=Course::with(['category', 'assigned_teams', 'team'])->get();

阅读更多:eager-loading-multiple-relationships 顺便说一句,正如@apokryfos 提到的,您应该使用Eloquent RelationshipsEager Loading 重构您的代码。

【讨论】:

    【解决方案2】:

    我假设您的CourseResource 中没有处理assigned_teams。 您需要扩展您的资源以尊重这种额外的关系。

    class CourseResource extends JsonResource
    {
    
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
    
                // return teams if they have been loaded
                'teams' => TeamsResource::collection($this->whenLoaded('assigned_teams')),
            ];
        }
    }
    

    这只是示例,因为您尚未提供 CourceResource 的代码,您需要根据需要对其进行更新。

    这里是相应 laravel 文档的链接:https://laravel.com/docs/8.x/eloquent-resources#conditional-relationships

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 2019-07-05
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多