Отношения в laravel 5.4 ond отображают данные - PullRequest
0 голосов
/ 28 мая 2018

У меня есть две таблицы, и я хочу отобразить все поля, где: question_id.Question = question_id.QuestionOption.Я не знаю, как это сделать в Laravel:

Schema::create('questions', function (Blueprint $table) {
    $table->increments('id');
    $table->string('question_text');
    $table->integer('points');
    $table->integer('temps_reponse');

    $table->integer('categories_id')->unsigned();
    $table->foreign('categories_id')->references('id')->on('categories');

    $table->integer('type_id')->unsigned();
    $table->foreign('type_id')->references('id')->on('types');

    $table->timestamps();

});

Schema::create('question_options', function (Blueprint $table) {
    $table->increments('id');
    $table->string('option_one');
    $table->string('option_two');
    $table->string('option_three');
    $table->string('correcte');

    $table->integer('question_id')->unsigned()->nullable();
    $table->foreign('question_id')->references('id')->on('questions');

    $table->timestamps();

});

мой цикл foreach, но он не работает:

@foreach ($question_options as $question_option)
    <tbody>
        <tr>
            <td>{{ $question_option->question->id }}</td>
            <td>{{ $question_option->question->question_text }}</td>
            <td>{{ $question_option->option_one }}</td>
            <td>{{ $question_option->option_two }}</td>
            <td>{{ $question_option->option_three }}</td>
            <td>{{ $question_option->question->points }}</td>                                 
        </tr>   
    </tbody>
@endforeach

1 Ответ

0 голосов
/ 28 мая 2018

Определение отношений в ваших моделях:

Модель вопроса:

class Question extends Model {
    public $table = 'questions';

    public function options() {
        return $this->hasMany(QuestionOption::class);
    }
}

ВопросОпция модели:

class QuestionOption extends Model {
    public $table = 'questions_options';

    public function question() {
        return $this->belongsTo(Question::class);
    }
}

Отныне вы можете получить доступ к опциям вопроса вариантов:

$question = Question::with('options')->first();

и на ваш взгляд:

@foreach($question->options as $question_option)
    <tbody>
        <tr>
            <td>{{ $question_option->question->id }}</td>
            <td>{{ $question_option->question->question_text }}</td>
            <td>{{ $question_option->option_one }}</td>
            <td>{{ $question_option->option_two }}</td>
            <td>{{ $question_option->option_three }}</td>
            <td>{{ $question_option->question->points }}</td>                                 
        </tr>   
    </tbody>
@endforeach

Вместо $question_option->question->question_text вы можете получить доступ question_textнепосредственно от $question объекта.

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