如何将多行表数据保存到laravel数据库



基本问题:如何上传我的表数据,使其可以正确保存?

在我看来,我有一个3列和多行表。使用foreach正确填充行:当数据进入控制器使用这个:$input = $request->all();我没有得到一个组织良好的数组系列,我完全失败的数据保存到数据库中。我的数据:

Array
(
[branches] => Array
(
[0] => 630
[1] => 632
[2] => 715
)
[date] => Array
(
[0] => 06/14/2022
[1] => 06/23/2022
[2] => 06/29/2022
)
[auditiors] => Array
(
[0] => 3
[1] => 5
[2] => 4
)
[disbursed] => Array
(
[0] => 797
[1] => 32
[2] => 234
)
[sample_selected] => Array
(
[0] => 798
[1] => 2324
[2] => 1233
)
[days_cases] => Array
(
[0] => 765
[1] => 21334
[2] => 12
)
[days_branches] => Array
(
[0] => 32
[1] => 123
[2] => 1223
)
[total_days] => Array
(
[0] => 797
[1] => 21457
[2] => 1235
)
)

所以从你的评论中我猜你想从数组中压缩值,比如

array(
[
$branches[0],
$dates[0]
...
],
[
$branches[1],
$dates[1]
...
],
)

然后

// preparing data for models
$combined = array_map(
null,
$request->get('branches'),
$request->get('date'),
$request->get('auditors'),
$request->get('disbursed'),
$request->get('sample_selected'),
$request->get('days_cases'),
$request->get('days_branches'),
$request->get('total_days'),
);

// saving
foreach ($combined as $data) {
// rename fields accordingly
// don't forget to provide $fillable array in ModelName
ModelName::create([        
'branches' => $data[0],
'date' => $data[1],
'auditors' => $data[2],
'disbursed' => $data[3],
'sample_selected' => $data[4],
'days_cases' => $data[5],
'days_branches' => $data[6],
'total_days' => $data[7]
]);
}

如果您为模型 提供自定义填充方法,则将是更美观的解决方案。

//Model
public function customFill($data){
// calling laravel default fill method
$this->fill([        
'branches' => $data[0],
'date' => $data[1],
'auditors' => $data[2],
'disbursed' => $data[3],
'sample_selected' => $data[4],
'days_cases' => $data[5],
'days_branches' => $data[6],
'total_days' => $data[7]
]);
// returning filled model to be able to use fluent methods
return $this;
}

then in controller

// preparing data for models
...
// saving
foreach ($combined as $data) {
(new ModelName)->customFill($data)->save();
}

相关内容

  • 没有找到相关文章

最新更新