Получить значение из сводной таблицы не работает должным образом - PullRequest
0 голосов
/ 24 апреля 2018

У меня есть форма для ввода пользователем информации для регистрации в конгрессе.

В форме есть эта часть для отображения обязательного атрибута, только если в пользовательском вопросе есть столбец «обязательный» со значением «1»:

  @foreach($selectedType['questions'] as $customQuestion)

    <div class="form-group">
        <label for="participant_question">{{$customQuestion->question}}</label>
        <p>REQUIRED VALUE:::::: {{$customQuestion->required }}</p>
        <p>REQUIRED VALUE:::::: {{$customQuestion->ticket_type->pivot->required}}</p>
         <p>REQUIRED VALUE:::::: {{$customQuestion}}</p>
        <input type="text" @if($customQuestion->required == "1") required @endif
           class="form-control" name="participant_question[]" value="">

    </div>
  @endforeach

Но это не работает, потому что "{{$customQuestion->required }}" в "<p>REQUIRED VALUE:::::: {{$customQuestion->required }}</p>" равно null, ничего не показывает.

"{{$customQuestion}}" показывает:

{"id":1,
 "question":"Whats your phone?",
 "type":"text","congress_id":1,
 "pivot":{"ticket_type_id":1,
 "question_id":1},
 "ticket_type":[{"id":1,
 "name":"test",
 "congress_id":1,
 "pivot":{"question_id":1,
 "ticket_type_id":1,"required":1}}]}

"{{$customQuestion->ticket_type->pivot->required}}" показывает: "Property [pivot] does not exist on this collection instance.".

Знаете ли вы, почему $customQuestion->required равен нулю?

Модели, имеющие отношение к вопросу:

// Congress model
class Congress extends Model
{

    // A congress has many ticket types
    public function ticketTypes(){
        return $this->hasMany('App\TicketType', 'congress_id');
    }
}

// TicketType Model

class TicketType extends Model
{
    public function congress(){
        return $this->belongsTo('App\Congress');
    }

    public function questions(){
        return $this->belongsToMany('App\Question', 'ticket_type_questions');
    }
}

// TicketTypeQuestion model

class TicketTypeQuestion extends Model
{

}

class Question extends Model
{

    public function ticket_type(){
        return $this->belongsToMany('App\TicketType', 'ticket_type_questions')
            ->withPivot('required');
    }
}

Таблица взаимосвязей релевантных для вопроса:

1 to many between congress and ticket types (a congress can have many ticket types)
1 to many between ticket types and ticket_type_questions (a ticket type can have many custom questions)
1 to many between questions and ticket_type_questions (a question can be associated with many ticket types)

Таблица ticket_type_questions имеет следующую структуру: id, ticket_type_id, question_id, required. Обязательный столбец равен 1, если пользовательский вопрос требуется для данного типа заявки, и 0, если не требуется.

"$selectedTypes" происходит из метода RegistrationController storeUserInfo ():

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']);
            //dd($selectedTypes);
            return redirect(route('congresses.registration',['id' => $id, 'slug' => $slug]));
        }

1 Ответ

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

Вам необходимо добавить ->withPivot(..) к вашему TicketType questions() отношению:

class TicketType extends Model
{
    public function questions(){
        return $this->belongsToMany('App\Question', 'ticket_type_questions')
            ->withPivot(['required']);
    }
}

Тогда вы можете сделать:

{{ $customQuestion->pivot->required }}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...