首页 > 解决方案 > 如何从两个不同的 Laravel 查询构建器中获取我的两个结果集以同时显示在同一页面上?

问题描述

我正在 Laravel 中构建一个测验应用程序。我有两个要从MySQL数据库中检索的数据表。这些表称为questionsanswers。对于这些表中的每一个,我还有两个查询生成器。一个questions查询生成器和一个answers查询生成器。

我在答案查询构建器之前创建了问题查询构建器,并在 Blade 的帮助下成功地检索和显示了我的数据。这些问题在我的造型中看起来很好。不久之后,我创建了我的答案查询构建器来从数据库中检索我的答案表。这很有效,因为我的答案明显出现了,除了包括我的问题和背景样式在内的所有其他内容都消失了。剩下的是一个带有答案和默认白色背景的页面。当我将路由资源方法web.php指向我的localhost:8000/questions页面时,就会发生这种情况。这是我想要展示一切的地方。

当然,这两种查询构建器方法都在它们自己的控制器文件中。QuestionsController.phpAnswersController.php。我尝试仅使用一个控制器文件和一个查询生成器来从我的数据库中检索问题和答案->join。我发现这很令人困惑,尤其是与我的分页方法结合使用时。我还了解到,当您有多个数据集时,划分控制器文件是更好的做法。我的猜测是我的 Blade 代码有问题,因为它的样式被弄乱了。

QuestionsController.php

public function index() 
    {
        $questions = DB::table('questions')->simplePaginate(1);                            
        return view('questions.questions', ['questions' => $questions]); 
    }

AnswersController.php

public function index() 
    {
        $answers = DB::table('answers')->simplePaginate(1);                            
        return view('answers.answers', ['answers' => $answers]); 
    }

问题.blade.php

@extends('home')
@if(count($questions))
    @foreach($questions as $question)
        <div class="row justify-content-center" style="margin-top: 200px; margin-left: 550px; position: absolute; z-index: 99;">
            <p>{{$question->question}}</p> 
        </div>
    @endforeach
@else 
    <p>How embarrassing. We couldn't even provide you a question. Worst quiz ever.</p> 
@endif 
// this is where my form goes
{{ $questions->links() }}

answers.blade.php

@if(count($answers))
    @foreach($answers as $answer)
        <div class="row justify-content-center" style="margin-top: 200px; margin-left: 550px; position: absolute; z-index: 99;">
            <p>{{$answer->answer}}</p> 
        </div>
    @endforeach
@else 
    <p>How embarrassing. We couldn't even provide you any answers. Worst quiz ever.</p> 
@endif 

网页.php

Route::resource('questions', 'QuestionsController');  
Route::resource('questions', 'AnswersController');

目标是让我的问题和答案都显示在同一页面上。造型完好无损。

PS 我知道我要返回两种不同的视图,一个QuestionsController.phpAnswersController.php. 我知道这可能是问题的路径。我只是不知道替代方案。

标签: laraveleloquentlaravel-bladelaravel-5.8laravel-query-builder

解决方案


在您的 web.php 中,您的答案控制器资源是否需要:

 Route::resource('answers', 'AnswersController');

而不是:

Route::resource('questions', 'AnswersController');

推荐阅读