php - Laravel:无法使用 Foreach 创建多个数据关系
问题描述
我在创建数据时遇到问题,数据返回 null 和错误。Maatwebsite/excel</code> import. In my import class, I want to create data with the relation, when I try the
dd
variable that contains child data its works just fine, but when I <code>saveMany()
完整性约束违规:1048 列“描述”不能为空
这是我的代码:
public function collection(Collection $rows) {
$parent = Parent::create([
'name' => $this->name,
'slug' => $this->slug,
'month' => $this->month,
]);
foreach ($rows as $row) {
$item = new Child([
'description' => $row['description'],
'status' => $row['status'],
]);
$items[] = $item;
}
$parent->childs()->saveMany($items);
}
解决方案
可能你在 foreach 中的 $row['description'] 有空值。
像这样编辑你的循环代码
foreach ($rows as $row) {
if(!empty($row['description]))
{
$item = new Child([
'description' => $row['description'],
'status' => $row['status'],
]);
$items[] = $item;
}
}
并编辑最后一行
if(!empty($items))
$parent->childs()->saveMany($items);
推荐阅读
- android - 如何在videoview中设置播放按钮图像png?
- django - Django 翻译仅部分工作
- javascript - Jquery ajax 将空值传递给 MVC 控制器
- javascript - JavaScript href 替换不起作用
- java - 创建一个对数组中的值求和并返回总数的方法
- python - 忽略 nan 的列的 Pandas mean()
- python - 我想从学生 id = id 的费用表中获取学生最后支付的费用
- firebase - 如何仅将静态文件部署到 Firebase 托管
- python - Python Web Scraping 返回空括号
- css - CSS 不适用于使用 create-react-library 创建的链接 React 库