【发布时间】:2021-12-12 10:35:14
【问题描述】:
下面给出的我的代码只向表中插入一行。对于$courseChapters 的chapter_content 数组中的每一组数据,我希望它作为CoursePublishChaptercontent 表中的新行添加,courseId 和points 字段的值对于此类数据的每一新行重复。对于示例,需要将 预期输出 中给出的 2 行新数据插入到表中,以用于下面给定的 var_export($courseChapters) 数据。有人可以告诉我如何实现这一目标吗?
foreach ($courseChapters['chapter_content'] as $chapter) {
$postdata['chapterId'] = $chapter['course_chapter_id'];
$postdata['contentTypeId'] = $chapter['content_type_id'];
$postdata['fileId'] = $chapter['file_id'];
$data=CoursePublishChaptercontent::create([
'courseId' => $courseChapters['courseId'],
'points' => $courseChapters['points'],
'course_chapter_id'=>$postdata['chapterId'],
'content_type_id'=>$postdata['contentTypeId'],
'file_id'=>$postdata['fileId']]);
}
var_export($courseChapters) 是一个数组,如下所示:
array (
'id' => 4,
'courseId' => 24,
'points' => 8,
'chapter_content' =>
array (
0 =>
array (
'course_chapter_id' => 4,
'file_id' => 3,
'content_type_id' => 1,
),
1 =>
array (
'course_chapter_id' => 4,
'file_id' => 4,
'content_type_id' => 2,
),
),
)
编辑
//$postdata=[];
$i=0;
foreach ($courseChapters['chapter_content'] as $chapter) {
$postdata[$i]['courseId'] = $courseChapters['courseId'];
$postdata[$i]['points'] = $courseChapters['points'];
$postdata[$i]['course_chapter_id'] = $chapter['course_chapter_id'];
$postdata[$i]['content_type_id'] = $chapter['content_type_id'];
$postdata[$i]['file_id'] = $chapter['file_id'];
$i++;
}
$data=CoursePublishChaptercontent::create($postdata);
预期/要求的输出:
[
"courseId" => 24
"points" => 8
"course_chapter_id" => 4
"content_type_id" => 1
"file_id" => 3
],
[
"courseId" => 24
"points" => 8
"course_chapter_id" => 4
"content_type_id" => 2
"file_id" => 4
]
当前输出:
array:2 [
0 => array:5 [
"courseId" => 24
"points" => 8
"course_chapter_id" => 4
"content_type_id" => 1
"file_id" => 1
]
1 => array:5 [
"courseId" => 24
"points" => 8
"course_chapter_id" => 4
"content_type_id" => 1
"file_id" => 3
]
]
【问题讨论】:
标签: php laravel postgresql eloquent laravel-8