2

我有一个遍历数组的 foreach 循环,并以雄辩的方式保存数据。当它像这样时它工作正常:

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.';
    }
}

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

4

2 回答 2

5

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

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

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

This allows $question to be accessed within the scope of the callback.

于 2016-03-09T17:59:07.873 回答
0

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

“firstOrNew 方法,如 firstOrCreate 将尝试在数据库中查找与给定属性匹配的记录。但是,如果找不到模型,则会返回一个新的模型实例。请注意,由 firstOrNew 返回的模型尚未持久化到数据库。您需要手动调用 save 来持久化它。

示例(使用您的 $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();

}
于 2016-03-09T18:33:55.567 回答