使用laravel从控制器调用数据从数据库到视图

时间:2017-02-28 03:06:36

标签: php mysql laravel laravel-5 laravel-5.2

控制器:

public function index() {
    $data = DB::table('tusers','tbills','tpackages')
    ->join('tbills', 'tusers.user_id', '=', 'tbills.user_id')
    ->join('tpackages', 'tbills.package_id', '=', 'tpackages.package_id')
    ->select('tusers.user_id','tusers.company_name','tusers.first_name', 'tbills.account_no', 'tpackages.package_name','tbills.start_date','tbills.end_date','tbills.bill_status')
    ->get();

    return View::make('account')->with('data',$data);
}

`

视图:

@forelse($data as $value)
    <td>{{ $value->user_id }}</td>
    <td>{{ $value->company_name }}</td>
    <td>{{ $value->first_name }}</td>
    <td>{{ $value->account_no }}</td>
    <td>{{ $value->package_name }}</td>
    <td>{{ $value->start_date }}</td>
    <td>{{ $value->end_date }}</td>
    <td>{{ $value->bill_status }}

我想从packagecontroller调用$ data到account.blade,但是有错误

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "tusers" does not exist
LINE 1: ... "tbills"."end_date", "tbills"."bill_status" from "tusers" i...
^ (SQL: select "tusers"."user_id", "tusers"."company_name", "tusers"."first_name", "tbills"."account_no", "tpackages"."package_name", "tbills"."start_date", "tbills"."end_date", "tbills"."bill_status" from "tusers" inner join "tbills" on "tusers"."user_id" = "tbills"."user_id" inner join "tpackages" on "tbills"."package_id" = "tpackages"."package_id")

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

table()中删除其他2个表名。这样的事情。

public function index() {
    $data = DB::table('users','bills','packages')
    ->join('bills', 'users.id', '=', 'bills.user_id')
    ->join('packages', 'bills.package_id', '=', 'packages.id')
    ->select('users.id','users.company_name','users.first_name', 'bills.account_no', 'packages.package_name', 'bills.start_date', 'bills.end_date', 'bills.bill_status')
    ->get();

    return view('account', ['data' => $data]);
}
请注意心灵栏目命名。我可能更改了一些名字,所以你必须确保你有正确的名字。

在您的视图中执行

@foreach( $data as $value )
    <td>{{ $value->company_name }}</td>
    ...
@endforeach

好像你正在跳过一些步骤。通过这个免费视频系列正确学习如何使用Laravel:https://laracasts.com/series/laravel-from-scratch-2017