【问题标题】:Sending more than one model (table) to the same view Laravel将多个模型(表)发送到同一个视图 Laravel
【发布时间】:2018-08-17 22:16:19
【问题描述】:

我曾试图寻找答案,但为此苦苦挣扎。我正在练习使用 MVC。我能够将一个完整的表从数据库返回到视图并显示它的内容。我正在努力的是对来自同一个数据库的第二个表做同样的事情。有没有办法将两个单独的表返回到同一个视图中?如果我想在同一页面(视图)中显示来自三个或更多单独表的数据怎么办。怎么可能做到这一点?我将不胜感激任何帮助和解释。如果我的解释不清楚,请告诉我。

控制器 DBController.php

namespace App\Http\Controllers\example;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class DBController extends Controller
{
    /**
     * Show a list of all of the application's users.
     *
     * @return Response
     */
    public function hakunamatata()
    {
        $tests = DB::table('somename')->get();                              

        return view('pages.testcursorfollow', ['tests' => $tests]);
    }
    public function testowanie()
    {
        $checks = DB::table('somename2')->get();

        return view('pages.testcursorfollow', ['checks' => $checks]);
    } 
}

我在 web.php 中的路线:(我知道两者的“kursor”部分不应该相同,但这就是想法,将它们都返回到相同的视图;或者三个,或者更多,如果需要)

Route::get('kursor', 'example\DBController@hakunamatata');
Route::get('kursor', 'example\DBController@testowanie');

我的看法testcursorfollow.php:

<table style="border: 1px solid black;">
  <tr>
    <th>ID</th>
    <th>col1</th>
    <th>col2</th>
    <th>col3</th>
    <th>col4</th>
    <th>col5</th>
  </tr>
  @if (isset($tests))
  @foreach ($tests as $user)
  <tr>
    <td>{{$user->id}}</td>
    <td>{{$user->col1}}</td>
    <td>{{$user->col2}}</td>
    <td>{{$user->col3}}</td>
    <td>{{$user->col4}}</td>
    <td>{{$user->col5}}</td>
  </tr>
@endforeach
@endif


</table>

<table style="border: 1px solid black;">
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Surname</th>
  </tr>

 @foreach ($checks as $check)
  <tr>
    <td>{{$check->id}}</td>
    <td>{{$check->Name}}</td>
    <td>{{$check->Surname}}</td>
  </tr>

@endforeach
</table>

【问题讨论】:

    标签: database laravel controller routing blade


    【解决方案1】:

    你可以用 compact 做到这一点。

    例如:

    function getStuff() {
      $posts = DB::table('posts')->get();
      $comments = DB::table('comments')->get();
    
      return view('pages.testcursorfollow', compact('posts', 'comments'));
    }
    

    【讨论】:

    • 对,我马上试试。谢谢尼克。
    • 太好了,成功了!好东西。我需要阅读一些关于“紧凑”的内容。
    • @RafalM 不错!这实际上很容易。您放在括号中的所有内容都将提供给您要返回的视图。
    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    相关资源
    最近更新 更多