我有點卡住了。Laravel:用戶可以有許多設備,但每個設備最多隻能屬於一個用戶
所以我有2個型號,User
和Device
。用戶可以有X個設備,但每個設備只能屬於最多1個用戶。
我定義的關係是這樣的:
class Device extends Model
{
public function user()
{
return $this->hasOne('App\User');
}
}
class User extends Authenticatable
{
public function devices()
{
return $this->hasMany('App\Device');
}
}
現在,我要爲我的設備概述 - 視圖。
class DeviceController extends Controller
{
public function showOverview()
{
$devices = Device::all();
return view('devices.overview')->with('devices', $devices);
}
}
在此查看我的foreach我的所有設備。
@foreach ($devices as $device)
<tr>
<td>{{ $device->id }}</td>
<td>{{ $device->serial }}</td>
<td>{{ $device->state }}</td>
<td><!-- Get user Name here by $device->user_id Foreign key --></td>
<td>
<a href="" class="btn btn-block btn-primary btn-sm">
<i class="fa fa-user" aria-hidden="true"></i> Profile
</a>
</td>
</tr>
@endforeach
還有,這裏的評論是我想要去獲得相關的用戶名。外鍵保存爲$device->user_id
,並引用users表的id。我怎樣才能得到那個用戶的名字?
謝謝。但是,當訪問我的路線時,我得到這個錯誤:'在你像寫下的那樣替換它之後調用未定義的方法Illuminate \ Database \ Query \ Builder :: all()'。 – Scarwolf
我已更新答案,對於錯字感到抱歉 –