Как правильно хранить каждый ответ в таблице ответов?(получение ошибки SQLSTATE [23000]) - PullRequest
0 голосов
/ 24 апреля 2018

У меня есть этот код ниже, чтобы:

  • создать запись в таблице участников с регистрационным идентификатором, ticket_type_, а также адресом электронной почты и именем каждого участника.Это первое для и работает нормально.
  • создайте запись в таблице ответов с идентификаторами участника (ов) из вышеприведенного шага и с question_id.Этот второй шаг не работает.При нажатии «Далее» появляется сообщение:

SQLSTATE [23000]: нарушение ограничения целостности: 1048 Столбец 'member_id' не может быть пустым (SQL: вставить в answers (question_id, * 1011)*, answer, updated_at, created_at) значения (00, 00, 2018-04-24 19:16:10, 2018-04-24 19:16:10))

//first for and is working fine
for($i = 0; $i < count($request->participant_name); $i++)
    $participant = Participant::create([
        'name' => $request->participant_name[$i],
        'surname' => $request->participant_surname[$i],
        'registration_id' => $registration->id,
        'ticket_type_id' => $request->ttypes[$i]
    ]);
// second for, this is not working
for($i = 0; $i < count($request->participant_question); $i++)
    $answer = Answer::create([
        'question_id' => $request->participant_question[$i],
        'participant_id' => $participant[$i],
        'answer' => $request->participant_question[$i],
    ]);

Знаете ли вы, где проблема?

Более подробное объяснение контекста:

У меня есть файл single.blade.php, который используется для отображениястраница с информацией о конгрессе.На этой странице сведений о конгрессе также есть форма, позволяющая пользователю выбрать билеты и количество каждого билета на конгресс.После того, как пользователь нажимает «Далее», код переходит к методу RegistrationController storeQuantities ():

public function storeQuantities(Request $request, $id, $slug = null){
    $ttypeQuantities = $request->get('ttypes');

    $all_participants = Congress::where('id', $id)->first()->all_participants;

    foreach($ttypeQuantities as $ttypeName => $quantity){
        if($quantity) {
            $ttype = TicketType::where('name', $ttypeName)->firstOrFail();
            $price = $ttype->price;

            $selectedType[$ttype->name]['quantity'] = $quantity;
            $selectedType[$ttype->name]['price'] = $price;
            $selectedType[$ttype->name]['subtotal'] = $price * $quantity;
            $selectedType[$ttype->name]['questions'] = $ttype->questions;
        }
    }
    Session::put('selectedTypes', $selectedTypes);
    Session::put('all_participants' , $all_participants);
    Session::put('customQuestions' ,  $selectedTypes[$ttype->name]['questions']);
    return redirect(route('congresses.registration',['id' => $id, 'slug' => $slug]));
}

Затем метод storeUserInfo() перенаправляет пользователя в registration.blade.php, где пользователю необходимо:

  • введите его имя, фамилию и адрес электронной почты
  • , затем для каждого выбранного билета введите имя и фамилию участника, который будет связан с этим конкретным билетом
  • , затем каждыйТип билета может иметь пользовательские вопросы, такие как «Какой у вас номер телефона?», поэтому, если пользователь выбрал на предыдущей странице тип заявки, у которого есть пользовательские вопросы, пользовательские вопросы также будут представлены пользователю, чтобы он мог ответить

Код Registration.blade.php для отображения полей для сбора вышеуказанных данных:

<form method="post" action="">
    {{csrf_field()}}
    <div class="form-group font-size-sm">
        <label for="name" class="text-gray">Name</label>
        <input type="text" required class="form-control" id="name"
               name="name" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
    </div>
    <div class="form-group font-size-sm">
        <label for="surname" class="text-gray">Surname</label>
        <input type="text" id="surname" required class="form-control" name="surname" value="{{ (\Auth::check()) ? Auth::user()->surname : old('surname')}}">
    </div>

<!-- other form fields -->

<!-- if the all_participants is 1 in the confernece table it should appear for each selected ticket a section for the user 
    that is doing the registration insert the name and surname of each paarticipant -->
    @if (!empty($all_participants))
        @if($all_participants == 1)
            @foreach($selectedTypes as $k=>$selectedType)
              @foreach(range(1, $selectedType['quantity']) as $test)
                  <h6>Participant - 1 - {{$k}}</h6> <!-- $k shows the ticket type name -->
                  <div class="form-group font-size-sm">
                      <label for="participant_name" class="text-gray">Name</label>
                      <input type="text" name="participant_name[]" required class="form-control" value="">
                  </div>
                  <div class="form-group font-size-sm">
                      <label for="participant_surname" class="text-gray">Surname</label>
                      <input type="text" required class="form-control" name="participant_surname[]" value="">
                  </div>
                   @foreach($selectedType['questions'] as $customQuestion)
                        <div class="form-group">
                            <label for="participant_question">{{$customQuestion->question}}</label>
                            <input type="text" required class="form-control" name="participant_question[]" value=""> 
                            <input type="hidden" value="{{ $customQuestion->id }} name="participant_question_id[]"/>


                        </div>
                    @endforeach
              @endforeach
        @endif
    @endif
    <input type="submit" href="#" value="Next"/>
  </form>

Затем, когда пользователь нажимает «Далее», код переходит в storeUserInfo ()

public function storeUserInfo(Request $request, $id, $slug = null, Validator $validator){
    $user = Auth::user();
    $registration = Registration::create([
        'congress_id' => $id,
        'main_participant_id' => $user->id,
        'status' => 'C',
    ]);
    // the code in this for is working
    for($i = 0; $i < count($request->participant_name); $i++)
        $participant = Participant::create([
            'name' => $request->participant_name[$i],
            'surname' => $request->participant_surname[$i],
            'registration_id' => $registration->id,
            'ticket_type_id' => $request->ttypes[$i]

        ]);
    // the code in this for is not working
    for($i = 0; $i < count($request->participant_question); $i++)
        $answer = Answer::create([
            'question_id' => $request->participant_question[$i],
            'participant_id' => $participant[$i],
            'answer' => $request->participant_question[$i],
        ]);
}

1 Ответ

0 голосов
/ 24 апреля 2018

Это потому, что $participant не является массивом, это объект Eloquent.

Перед созданием всех участников (до цикла for) создайте пустой массив:

$participants = [];

Измените следующую строку

$participant = Participant::create([

на

$participants[] = Participant::create([

и, наконец, измените строку при создании ответов:

'participant_id' => $participants[$i],

на

'participant_id' => $participants[$i]->id,

Это должно исправить ваш код.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...