所以我有一个功能:
$v->firstOrCreate([
"test_page" => $vessel["test_page"],
"deck" => $vessel->deck,
"test_order" => $vessel->test_order,
"component_name" => $vessel->component_name,
]);
此代码重复但具有不同的字段集。所以我尝试通过辅助函数来减少代码:这将获取一个字段数组并将其作为参数传递给函数,但也在该函数内部执行某种映射值。我知道描述有点令人困惑,我不确定这是不是一件事。 在PHP中有什么方法我可以做类似
的事情$field = ["field1","field2","field3","field4","field5",]
$model->firstOrCreate(
foreach ($field as $i) {
$i => $data[$i];
}
);
谢谢!
答案 0 :(得分:0)
如果$data
与$fields
具有相同的字段,请执行以下操作:
Model::firstOrCreate($data);
如果必须使用循环提取一些字段,请在函数调用之前执行:
$fields = ["field1","field2","field3","field4","field5",]
$attributes = [];
foreach ($fields as $field) {
$attributes[$field] = $data[$field];
}
$model->firstOrCreate($attributes);