我有一个Laravel作业,它设置一些数据然后使用数据在数据库中创建一个条目。数据库表中的所有字段均为NULL
。 custom_variables
字段是使用自定义方法getByPrefix()
设置的。
MyJob.php
<?php
class MyJob implements ShouldQueue {
public function __construct($input) {
$this->input = $input;
}
public function handle() {
$data = $this->getData();
MyModel::create($data);
}
protected function getData() {
if (isset($this->input['name'])) {
$data['name'] = $this->input['name'];
}
$data['custom_variables'] = $this->getByPrefix('custom-');
if (isset($this->input['surname'])) {
$data['surname'] = $this->input['surname'];
}
return $data;
}
/**
* Filter the input by the provided prefix
* and return matching input data.
* @return null|string
*/
protected function getByPrefix($prefix) {
$this->input= array_filter($this->input, function($k) use ($prefix) {
return strpos($k, $prefix) !== false;
}, ARRAY_FILTER_USE_KEY);
if (count($this->input) === 0) {
return null;
}
$data = array();
foreach ($this->inputas $k => $v) {
array_push($data, array($k => $v));
}
if (empty($data)) {
return null;
}
return json_encode($data);
}
}
问题是,如果我在中间保持对getByPrefix()
的调用,那么当存储记录时,$data['surname']
的值始终为NULL
,即使输入中存在surname
。
当我将调用移至getByPrefix()
到脚本末尾时,$data['surname']
设置正确。
为什么会发生这种情况?是因为我可能从getByPrefix()
方法返回JSON?不要这么认为,但谁知道呢。
我尝试将getByPrefix()
的正文包裹在try-catch
中 - 但是没有任何错误,custom_variables
字段始终在数据库中设置。
知道这里可能会发生什么吗?
更新
示例输入数据:
array(
'name' => 'John',
'surname' => 'Doe',
'custom-var' => 'customValue'
)
输出(应用getByPrefix()
后):
array(
'name' => 'John',
'custom_variables' => "[{"custom-var":"customValue"}]"
)
答案 0 :(得分:1)
正是因为这部分:
$this->input= array_filter($this->input, function($k) use ($prefix) {
return strpos($k, $prefix) !== false;
}, ARRAY_FILTER_USE_KEY);
您正在过滤输入并将结果覆盖到它。尝试使用其他变量。
$input= array_filter($this->input, function($k) use ($prefix) {
return strpos($k, $prefix) !== false;
}, ARRAY_FILTER_USE_KEY);
您获得name
但不是surname
的原因仅仅是因为您在调用方法之前设置了名称,而后者是在之后设置的。