我正在嘗試使用 laravel 構建一個小型 crud 應用程式。
在我的資料庫中,我有兩個公司和員工表。
公司 ID 是員工表的外鍵值。
用戶可以在創建新員工時從下拉串列中選擇公司。
我的問題是當我嘗試在表格中顯示我的用戶詳細資訊時,如何顯示公司名稱,因為它當前將公司 ID 存盤在我的員工表中?
以下是我在 EmployeeController 中的索引函式
public function index()
{
$data = Employee::latest()->paginate(10);
return view('employees.index', compact('data'))->with('i', (request()->input('page', 1) - 1) * 10);
}
這是我在索引刀片上的表。
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone </th>
<th>Action</th>
</tr>
@if(count($data) > 0)
@foreach($data as $row)
<tr>
<td>{{ $row->first_name }} {{ $row->last_name }}</td>
<td>{{ $row->email }}</td>
<td>{{ $row->phone }}</td>
<td>
<a href="{{ route('employees.show', $row->id) }}" class="btn btn-primary btn-sm">View</a>
<a href="{{ route('employees.edit', $row->id) }}" hljs-string">">Edit</a>
<a href="#" data-toggle="modal" data-target="#delUser">Delete</a>
<!-- Delete company Modal -->
<div class="modal fade" id="delUser" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>Do you sure want to delete this company? This operation cannot be reverted!</p>
</div>
<div class="modal-footer">
<form action="{{ route('employees.destroy',$row->id) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit" hljs-string">">Delete</button>
<button type="button" hljs-keyword">default" data-dismiss="modal">Cancel</button>
</form>
</div>
</div>
</div>
</div>
</td>
</tr>
@endforeach
@else
<tr>
<td colspan="5" hljs-string">">No Data Found</td>
</tr>
@endif
</table>
如何顯示用戶的公司名稱,而不是 ID....
我的公司表

我的員工表

uj5u.com熱心網友回復:
您必須在Employee模型中定義關系https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-inverse
public function company()
{
return $this->belongsTo(Company::class);
}
接下來,在控制器上,您必須急切加載:
$data = Employee::with('company')->latest()->paginate(10);
而且,在視圖中,您可以獲得員工姓名:
$row->company->name
您可以在https://laravel.com/docs/9.x/eloquent-relationships#eager-loading上找到更多關于急切加載的資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/514631.html
標籤:php拉拉维尔
