gpt4 book ai didi

php - Laravel Eloquent foreach 循环

转载 作者:行者123 更新时间:2023-12-02 21:06:06 24 4
gpt4 key购买 nike

我有一个 foreach 循环,它遍历一个数组,并用 Eloquent 方式保存数据。当它像这样的时候它工作得很好:

foreach($questions['questions'] as $question) {

$questionObject = Question::create([
'external_id' => $question['id'],
'text' => $question['question_text'],
'type' => $question['question_type'],
'image' => (array_key_exists('question_image', $question)) ?
$question['question_image'] : ''
]);

}

但是当我添加 if 条件时,我收到 undefined variable 问题错误。

foreach($questions['questions'] as $question) {

if(!$question = Question::where('id', $question['id'])->where(
function($query){
$query->where('updated_at','<', $question['updated']);
}})->first()) {

$questionObject = Question::create([
'external_id' => $question['id'],
'text' => $question['question_text'],
'type' => $question['question_type'],
'image' => (array_key_exists('question_image', $question)) ?
$question['question_image'] : ''
]);
} else {
return 'Question: '.$question['external_id'].' already exist.';
}
}

如果有人可以帮助我,我将非常感激,提前致谢!

最佳答案

您没有将 $question 注入(inject)回调函数中。您需要使用 use 关键字:

if(!$question = Question::where('id', $question['id'])->where(function($query) use ($question) { $query-  >where('updated_at','<', $question['updated']); })->first()) {

请注意,我在 function($query) 之后添加了 use ($question)

这允许在回调范围内访问$question

关于php - Laravel Eloquent foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35899028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com