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

create a list of data with value from multiple one to many relationsship

我有 table 结构,其中包含从下拉列表中选择的 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 之后,我想从 table TeacherCourse 中获取与 $teacherCourse->teacher_id 关联的所有值 并合并值并按以下格式创建数组:

{
    "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');
}

我试图使用此操作获取值但失败了。如何通过从多个 table?

获取值来创建单个数组
$teacherCourse = $teachercourse->program->map(function ($program) 
{
    return $program->name;
});

试试这个:

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

希望对你有帮助