创建一个具有多个一对多关系值的数据列表

问题描述 投票:0回答:1

我有表结构,其中包含从下拉列表中选择的ID列表。让我们说以下格式:

id,teacher_id,batch_id,course_id,program_id,depart_id

这些字段通过ajax调用保存到数据库。现在我想得到与这个id's相关的名字

我有一个像这样的功能:

public function store(StoreEmployeesRequest $request)
{
   $teacherCourse = TeacherCourse::create($request->all());
}

在这里,在创建了TeacherCourse之后,我想从表$teacherCourse->teacher_id获取与TeacherCourse相关的所有值,并合并该值并按以下格式创建数组:

{
    "id":8,
    "program":"Master of Computer", //with program_id from program table
    "course":"software engineering" //with course_id from course table
},
{
    "id":7,
    "program":"Bachelor of Pharmacy", //with program_id from program table
    "course":"Structure Programing" //with course_id from course table
}

TeacherCourse的关系

public function course()
{
  return $this->belongsTo(Course::class,'course_id');
}

public function program()
{
  return $this->belongsTo(Program::class,'program_id');
}

我试图使用此操作获取值但失败了。如何通过从多个表中获取值来创建单个数组?

$teacherCourse = $teachercourse->program->map(function ($program) 
{
    return $program->name;
});
laravel laravel-5.5
1个回答
1
投票

试试这个:

$teacherCourse = $teachercourse->map(function ($teacherCourse) 
{
    return [ 
             'id' => $teacherCourse->id,
             'program' => $teacherCourse->program()->pluck('name'),
             'course' => $teacherCourse->course()->pluck('name');
           ];
})->toArray();

我希望能帮助你

© www.soinside.com 2019 - 2024. All rights reserved.