0

请帮助我在我的数据库表问题中有两个属性选项 [] 和正确答案 [] 所以,我只想将正确答案存储在数据库中,而不是全部存储在数据库中,因为如果我选中一个选项然后我取消选中,它存储在数据库也是数据库中的错误答案 图片

这是我的代码:

  <div>
        @foreach($options as $index => $option)
            <div class="flex items-center mb-2" wire:key="{{$index}}-option">
                    <input wire:model="answers.{{ $option }}" name="answers.{{ $option }}" id="{{ 'answers'.rand() }}" 
                    value="answers.{{ $index }}" type="checkbox">
                      <input type="text" wire:model="options.{{ $index }}"
                    class="w-full px-3 py-2 border rounded bg-white flex-1 mr-2"
                    placeholder="Option ({{ $this->keys($index) }})">
            </div>
            @error('options') <span style="color:red"class="error">{{ $message }}</span> @enderror

        @endforeach
    </div>
 <div wire:key="submit-button">
        <button class="btn btn-success btn-lg">Create</button>
    </div>


 public function create()
{
    $this->validate([
        'question' => ['required', 'string', 'min:4', 'max:190'],
        'options' => ['required', 'array'],
        'options.*' => ['required', 'string'],
        'answers' => 'required' ,
        'type'=>'required',
        'titre'=>['required', 'string', 'min:4', 'max:190'],
    ]);


    $this->order=\App\Questions::where('exam_id',$this->exam->id)->count();
    $question=new Questions();
    $question->exam_id = $this->exam->id;
    $question->title = $this->titre;
    $question->question =$this->question; 
    $question->number_of_options = count($this->options); 
    $question->order = $this->order; 
    $question->response_type = $this->type; 
    $question->options =json_encode($this->options, JSON_UNESCAPED_UNICODE);
    $question->correct_answers =json_encode($this->answers, JSON_UNESCAPED_UNICODE);
    $question->save();

    $this->resetQuestion();
    $this->mount($this->exam);
    session()->flash('message', 'Ajout effectué avec succés.');
     $this->emit('closeModal');
    }
4

1 回答 1

2

错误的答案可以用array_filter($this->answers)

尝试这样的事情......

public function updatedAnswers()
{
    $this->answers = array_filter($this->answers);
}

在https://laravel-livewire.com/docs/lifecycle-hooks查看 Livewire 的生命周期挂钩

于 2020-06-24T07:08:04.417 回答