簡體   English   中英

如何從多個表中獲取數據並在Laravel中使用'-> with()'發送到html

[英]How to get data from multiple tables and send to html with '->with()' in laravel

我必須使用表“用戶”和“部門”,我想從兩個表中獲取數據並以html格式放置。 這是我的代碼不起作用,因為其中缺少某些內容。 這是控制器的代碼:

 public  function showProfileForm($id){
    $user = DB::table('users')->where('id','=',$id)->get();

    $dpt = DB::table('departments')->orderBy('department_name','asc')->get();
    return view('profile.showProfile')->with(['selDpt', $dpt, 'user', $user]);
}

get()方法將數據檢索為多維數組。 因此,當您僅檢索一個數組時,則必須在查詢末尾使用first()方法。 因此,只需將查詢從

$user = DB::table('users')->where('id','=',$id)->get();
to 
$user = DB::table('users')->where('id','=',$id)->first();

現在,您必須按array傳遞數據。 所以只要改變線

return view('profile.showProfile')->with(['selDpt', $dpt, 'user', $user]);
To
return view('profile.showProfile')->with(['selDpt' => $dpt, 'user' => $user]);

shoProfile.blade.php

您必須使用$selDpt$user變量來使用或回顯數據。 希望它能工作。

https://laravel.com/docs/5.4/views#passing-data-to-views了解更多

您可以使用以下語法將多個變量傳遞給視圖:

return view('profile.showProfile', [
    'selDpt' => $dpt,
    'user' => $user
]);

https://laravel.com/docs/5.4/views#passing-data-to-views

或者,您可以使用PHP函數compact() http://php.net/compact

$user = DB::table('users')->where('id','=',$id)->get();
$dpt = DB::table('departments')->orderBy('department_name','asc')->get();

return view('profile.showProfile', compact('dpt', 'user'));

您的視圖中將有$user$dpt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM