[英]Data fetching in a one to many relationship in laravel
我想從數據庫中獲取數據,但是當我嘗試從另一個表中獲取數據時卻卡住了。
這是我要執行的操作,當用戶登錄到網頁時,他將能夠看到人員姓名列表。 通過單擊他們的姓名,用戶將被重定向到另一個頁面,該頁面將顯示該人的詳細信息,例如姓名,地址和電子郵件。 但是因為他們太多(假設有200個人)
問題:
Q1。 我如何將用戶重定向到名稱的另一個頁面(例如:jack,用戶單擊jack name,jack id = 1,如何將其重新關聯到外鍵user_id = 1)
Q2。 我如何做一個循環來獲取他們的信息,而不是一一指定(例如:我不想一直說id = 1,是否有像id ++這樣的東西可以幫助自動添加)
home.blade.php
<table class="table table-bordered">
<tr>
<th><strong><big>Name AS PER NRIC/PASSPORT: </big></strong></th>
</tr>
<td>
<tr>
@foreach($data as $value)
<tr>
<th><a href="www.google.com"> {{$value->Name}}</a></th> --> I don't know how to redirect it to show user details
</tr>
@endforeach
</tr>
</tr>
</table>
控制者
public function index()
{
return view('home');
}
public function getData(){
$data['data'] = DB::table('personal_infos')->get()->sortByDesc('upload_time');
if(count($data)>0){
return view('home',$data);
}else{
return view('home');
}
}
}
路線
Route::get('/test','testController@getData');
personal_info模型
class personal_info extends Eloquent
{
protected $fillable = array('Email', 'Name', 'address');
protected $table = 'personal_infos';
protected $primaryKey = 'id';
public function user_infos() {
return $this->hasMany('App\user_info,'user_id');
}
public function user_info1s() {
return $this->hasMany('App\user_info1','user_id');
}
}
user_info和user_info1模型
class user_info1 extends Eloquent
{
protected $fillable = array('hobby','sport','user_id');
public function personal_infos() {
return $this->belongsTo('App\personal_info', 'user_id', 'id');
}
首先添加一條路線
Route::get('/test/{id}','testController@getPerson')->name("showPerson");
然后設置重定向
<a href="{{route('showPerson', $value)}}">
使用此行代替您的href =“ www.google.com”
使testController的getPerson()返回一個新頁面,在該頁面上,打印出一個人的所有信息。
我也建議您使用Google Laracast並觀看所有免費視頻。 它們大約有30個,它們使您對laravel框架有了很好的了解
更改頁面的鏈接以將您重定向到詳細信息頁面:
<th><a href="{{route('user.show',['id'=>$value->id])}}"> {{$value->Name}}</a></th>
路線應為:
Route::get('user/show/{id}','testController@getInfo')->name("user.show");
控制器應為:
public function getInfo($id) {
$user_info1 = user_info1::where('user_id',$id)->get();
return $user_info1;//change this with your view
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.