![](/img/trans.png)
[英]Quick retrieve data from different tables using Laravel eloquent relationships
[英]Retrieve data from multiple tables using their relationships-Laravel
我有一個需要完成的表,目前它有 3 列 DATE、SHIFT 和 STATION。
我只想要附加到登錄用戶的數據。
我有一個 pivot 表,我可以在其中調用 DATE 和 SHIFT 的數據,但 Stations 是一個單獨的表,
我的 pivot 表用於顯示 USER 和 SHIFTS 之間的多對多關系,稱為 shift_user。 這行得通,STATIONS 表關系是與 USER 的一對多關系,因為用戶將屬於一個站,但一個站將有多個用戶
站 model
public function user()
{
return $this->hasMany('App\User');
}
}
用戶 Model
public function station()
{
return $this->belongsTo('App\Station');
}
Controller 項目
$user = Auth::user();
return view('layouts/timesheet/index', ['user' => $user]);
}
刀片視圖將信息獲取到表中
<table class="table table-sm table-success">
<tr>
<th scope="col">DATE/DAY</th>
<th scope="col">SHIFT</th>
<th scope="col">STATION</th>
</tr>
<tbody class="table-light">
@foreach ($user->Station as $station)
@endforeach
@foreach ($user->shifts as $shift)
<tr>
<td>{{ $shift->created_at }}</td>
<td>{{ $shift->Name }}</td>
<td>{{ $station->Name }}</td>
</tr>
@endforeach
這是我要填寫的表格的圖片。我希望顯示站名,但我只是得到這個我認為是用戶 ID 的 ID
請讓我知道我可以做些什么來通過關系調用另一個表中的數據? 感謝您的任何幫助
確保創建的 function 與在 Blade View 上調用它時相同。
Station.php
public function user()
{
return $this->belongsTo('App\User');
}
用戶.php
public function stations()
{
return $this->hasMany('App\Station');
}
然后在刀片視圖上,試試這個:
@foreach($user as $u)
<tr>
<td>{{ $u->shift->created_at }}</td>
<td>{{ $u->shift->Name }}</td>
<td>{{ $u->stations->name }}</td> // I assume the column in stations table is "name"
</tr>
@endforeach
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.