Laravel eloquent foreach 循环

Laravel eloquent foreach loop

我有一个遍历数组的 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 条件时,出现未定义变量问题错误。

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 注入回调函数。您需要使用 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

您尝试过使用 firstOrNew() 吗? Laravel 文档 ->

"The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it."

示例(使用您的 $question 值):

foreach($questions['questions'] as $question) {
 $questionObject = Question::firstOrNew(
                array(
          'external_id' => $question['id'],
          'text' => $question['question_text'],
          'type' => $question['question_type'],
          'image' =>$question['question_image'] 

                )
        );

$questionObject->external_id = $question['id'];
$questionObject->text = $question['text'];
.
.
.
$questionObject->save();

}