laravel - 如何从两个不同的 Laravel 查询构建器中获取我的两个结果集以同时显示在同一页面上?
问题描述
我正在 Laravel 中构建一个测验应用程序。我有两个要从MySQL
数据库中检索的数据表。这些表称为questions
和answers
。对于这些表中的每一个,我还有两个查询生成器。一个questions
查询生成器和一个answers
查询生成器。
我在答案查询构建器之前创建了问题查询构建器,并在 Blade 的帮助下成功地检索和显示了我的数据。这些问题在我的造型中看起来很好。不久之后,我创建了我的答案查询构建器来从数据库中检索我的答案表。这很有效,因为我的答案明显出现了,除了包括我的问题和背景样式在内的所有其他内容都消失了。剩下的是一个带有答案和默认白色背景的页面。当我将路由资源方法web.php
指向我的localhost:8000/questions
页面时,就会发生这种情况。这是我想要展示一切的地方。
当然,这两种查询构建器方法都在它们自己的控制器文件中。QuestionsController.php
和AnswersController.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.php
在AnswersController.php
. 我知道这可能是问题的路径。我只是不知道替代方案。
解决方案
在您的 web.php 中,您的答案控制器资源是否需要:
Route::resource('answers', 'AnswersController');
而不是:
Route::resource('questions', 'AnswersController');
推荐阅读
- html - 如何并排排列html标签和输入
- python - plotly.py:改变线条不透明度,使标记不透明
- react-native - 更改状态后重新渲染当前屏幕
- excel - 如何合并csv文件中的两个单元格
- apache-kafka - Kafka Connect 从同一主题导出多种事件类型
- laravel-5.6 - FormRequest 错误返回带有错误数组键的数组
- javascript - knexfile.js 不读取 Dotenv 变量
- python - Python 仅列出我创建的变量
- node.js - 如何从bitgo Js中创建钱包后收到的响应数组中获取特定值
- c# - 从 C# 代码更新访问表