簡體   English   中英

如何在Laravel中對相關模型使用預先加載

[英]How to use eager loading for related models in Laravel

我有以下型號:

  • 約會[屬於時間段| [屬於用戶]
  • 時隙[hasMany約會]
  • 用戶[hasOne約會| HasOne詳細信息]
  • 詳細信息[屬於用戶]

我試圖使用以下查詢從約會模型(約會具有一個用戶,該用戶具有一個Details記錄)開始加載Details數據:

$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,但在其他調用中工作正常。 這里發生了什么?

確保所有關系方法都已返回 似乎其中之一沒有返回Relation定義。

您不能在關系定義中使用$ 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM