【发布时间】:2019-03-10 14:36:42
【问题描述】:
我有一辆餐桌车。该表具有字段 - created_by 和edited_by。每次创建或编辑车辆时,该特定用户的 ID 都会保存到此列中。 在显示此表详细信息的显示视图中,我想显示用户名而不是 ID。我在这里错过了什么或做错了什么?
我与用户关联的车辆模型:
class Vehicle extends Model
{
public function customer(){
return $this->belongsTo('App\Customer','customer_id');
}
public function user(){
return $this->belongsTo('App\User','edited_by');
}
}
显示数据的控制器:
public function show($id)
{
$vehicle = Vehicle::find($id);
$files = File::where('vehicle_id',$id);
return view('vehicles.show')->with('vehicle',$vehicle)
->with('files',$files);
}
查看
<tr>
<th>Created By</th>
<td>{{$vehicle->user->name}}</td>
</tr>
<tr>
<th>Last Edited By</th>
<td>{{$vehicle->user->name}}</td>
</tr>
我放置了hasmany关系的用户模型:
class User extends Authenticatable
{
public function vehicles(){
return $this->hasMany('App\Vehicle');
}
}
使用hasmany 我可以显示created_by 或edited_by 名称。如何同时显示 created_by 和edited_by 名称?
【问题讨论】:
标签: laravel