我有一个关系,我尝试用该关系插入模型中,当我只添加电话号码时,一切都很好,但是当我添加为type_id的secound字段时,我无法处理,因为它不会将secound字段插入下表是我在控制器存储中的操作方式,我希望我的用户能够发送无限的电话号码,并且每个用户都有一个type_id,我该如何实现 :
public function store(StoreHome $request)
{
$validated = $request->all();
if (!$validated) {
return $this->sendError('Validation Error.', $validated->errors());
}
$home = Home::create($validated);
$phones = [];
$type_id = [];
$numbers = $request->input('phones');
$type_id = $request->input('type_id');
foreach($numbers as $number => $item){
$phones[] = [
'phone' => $number
];
$types[] = [
$type_id[] = [
'type_id' => $type_id[$item]
]
];
}
$home->phones()->createMany($phones);
return new HomeResource($home);
答案 0 :(得分:0)
您将$phones
传递给createMany
,此变量不包含任何type_id
,因为您将它们放入了$types
变量中,而且该变量没有声明(我想您拼写错误了) $type_id = [];
代替$types = [];
答案 1 :(得分:0)
示例解决方案;
$datas = [];
foreach($numbers as $number => $item){
array_push($datas, [$number => $type_id[$item]]);
}
foreach ($datas as $key => $value) {
Home::create([
'phone' => $key,
'type_id' => $value
]);
}