2016-08-04 19 views
1

我有點卡住了。Laravel:用戶可以有許多設備,但每個設備最多隻能屬於一個用戶

所以我有2個型號,UserDevice。用戶可以有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。我怎樣才能得到那個用戶的名字?

回答

2

首先,你應該對所有設備渴望負載相關的用戶,以避免每次訪問相關一次額外的數據庫查詢用戶模型。

更換

$devices = Device::all(); 

$devices = Device::with('user')->get(); 

其次,爲了獲得相關的用戶對象在模板中只是做到以下幾點:

<td>{{ $device->user->name }}</td> 
+0

謝謝。但是,當訪問我的路線時,我得到這個錯誤:'在你像寫下的那樣替換它之後調用未定義的方法Illuminate \ Database \ Query \ Builder :: all()'。 – Scarwolf

+0

我已更新答案,對於錯字感到抱歉 –

0
$device->user->name // or other properties of user 

Device型號

return $this->belongsTo("App\User"); 

hasOne當外鍵是不是在引用表應該被使用。在你的情況下,外鍵user_id是在引用表devices,因此這是一個belongsTo關係

0

你有正確的您的用戶模型中的關係設置,但是相反在您的設備型號上應該使用belongsTo()方法,而不是hasOne()方法。

class Device extends Model 
{ 
    public function user() 
    { 
     return $this->belongsTo(App\User::class); 
    } 
} 

然後,您應該能夠使用在刀片模板下面給定設備獲取用戶的姓名。

{{ $device->user->name }} 

當你還訪問,你會遍歷該裝置結果每個模型的用戶關係,你不妨貪婪加載用戶關係的查詢量最小化到您的數據庫

$devices = Device::with('user')->get(); 

您還可以查詢設備只爲給定用戶

$user->devices 
相關問題