我具有从下拉列表中选择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;
});
答案 0 :(得分:1)
尝试一下:
$teacherCourse = $teachercourse->map(function ($teacherCourse)
{
return [
'id' => $teacherCourse->id,
'program' => $teacherCourse->program()->pluck('name'),
'course' => $teacherCourse->course()->pluck('name');
];
})->toArray();
希望对您有帮助