2016-01-13 51 views
1

我有以下型號:如何使用預先加載相關模型Laravel

  • 預約[屬於關聯時隙| belongsTo User]
  • 時間段[hasMany Appointment]
  • User [hasOne Appointment | HasOne詳情]
  • 詳細[屬於關聯用戶]

我想急於負荷約會模型開始的詳細數據(預約有一個用戶,其中有一個詳細記錄)使用以下查詢:

$apps = Appointment::with('timeslot')->with('user')->with('user.details')->get(); 

呼叫引發以下錯誤在Builder.php成員函數addEagerConstraints()非對象

爲什麼我在這裏調用非對象,爲什麼我的查詢不工作?

編輯:

這是我的用戶模型的關係:

public function details() { 
    dd($this->role_id); 
    switch($this->role_id) { 
     case 3: 
      return $this->hasOne('App\CandidateDetails', 'user_id'); 
      break; 
     case 2: 
      return $this->hasOne('App\EmployerDetails', 'user_id'); 
      break; 
    } 

} 

我知道,這將使用數據透視表可以更好地實現,它是一個學習的過程。 dd()在被我的查詢調用時返回null,但它在其他調用中正常工作。這裏發生了什麼?

回答

2

確保您在所有關係方法中都有返回。看起來他們中的一個沒有返回關係的定義。

你不能在關係定義中使用$ this--當構建查詢時,模型的屬性將被忽略,所以$ this-> role_id將給出null,並且不會返回任何關係。

爲了使其工作,你應該定義2個獨立的關係:

// User.php 
public function candidateDetails() { 
    return $this->hasOne('App\CandidateDetails', 'user_id'); 
} 

public function cemployerDetails() { 
    return $this->hasOne('App\EmployerDetails', 'user_id'); 
} 

public function getDetailsAttribute() { 
    switch($this->role_id) { 
    case 3: 
     return $this->candidateDetails; 
    case 2: 
     return $this->employerDetails; 
    } 
} 

// ...and then... 
$user = User::with('candidateDetails', 'employerDetails')->findOrFail($userId); 
// depending on user's role you'll get either candidate or employer details here 
$details = $user->details; 
+0

嗯,看在我原來的職位編輯 – matthiasdv

+0

不能使用$此有關的定義 - 模型的屬性會當查詢被建立時,這是不會啓動的,所以$ this-> role_id將會返回null,並且不會返回任何關係。 –

+0

那麼實現它的最優雅的方法是什麼?我有一個在用戶表上運行的用戶模型。每個記錄_either_與候選人或僱主表有關係。 – matthiasdv