laravel 5.4中的关系显示数据

时间:2018-05-27 23:46:56

标签: laravel-5.4

我有两个表,我想显示所有字段:pip。我不知道Laravel怎么做:

question_id.Question = question_id.QuestionOption

我的foreach循环但是不起作用:

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();

});

1 个答案:

答案 0 :(得分:0)

在模型中定义关系:

问题模型:

MGET

问题选择模型:

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

相关问题