2015-12-02 237 views
1

我有以下設置爲我的雄辯型號/ DB關係:查詢雄辯關係

Student有許多PhdReport

PhdReport有一個Link

我需要得到Student爲什麼會產生(單)最近PhdReport(由屬性date_to)是6個月以上和連接到所述PhdReport具有Link「完整」的status

我試圖做到這一點使用雄辯的關係,我是很新,查詢的關係,所以我想知道是否有到一個我正在一個更好的辦法的概念。

下面是相關的代碼至今:

PhdReport.php

public function link() 
{ 
    return $this->belongsTo(\App\Models\Link::class); 
} 

Student.php

public function phdReport() 
{ 
    return $this->hasMany(\App\Models\PhdReport::class); 
} 

public function latestPhdReport() 
{ 
    return $this->hasOne(\App\Models\PhdReport::class)->latest('date_to'); 
} 

/* this doesn't work! */  
public function lastPhdReportSixMonthsAgo() 
{ 
    $sixMonthsAgo = \Carbon\Carbon::now()->subMonth(6); 

    return $this->whereHas('latestPhdReport', function ($query) use ($sixMonthsAgo) { 
     $query->where('date_to', '<=', $sixMonthsAgo); 
    }); 
} 

這是我最好的拍攝,但迄今爲止我我不確定第一個whereHas是否適用於第二個whereHas a LSO?

$sixMonthsAgo = \Carbon\Carbon::now()->subMonth(6); 

$students = $this->student 
    ->whereHas('phdReport.link', function ($query) { 
     $query->where('status', 'complete'); 
    }) 
    ->whereHas('latestPhdReport', function ($query) use ($sixMonthsAgo) { 
     $query->where('date_to', '<=', $sixMonthsAgo); 
    }) 
    ->get(); 

如果我運行:

$students = $this->student 
    ->has('lastPhdReportSixMonthsAgo') 
    ->get(); 

我得到:

BadMethodCallException in Builder.php line 1994: 
Call to undefined method Illuminate\Database\Query\Builder::getRelated() 

任何建議,將不勝感激!

+0

這將做http://softonsofa.com/querying-relations-in-laravel-get-models-where-latest-相關 - 是/ –

+0

@JarekTkaczyk感謝您的鏈接。我現在有一個工作解決方案,但它肯定需要一些微調。一旦我滿意,我會發佈一個答案。再次感謝您的幫助 - 非常感謝。 – haakym

+1

很酷。完成後分享您的代碼。 –

回答

0

這是我目前的解決方案,我還沒有來得及重構,但是我敢肯定,它可以通過做只能查詢並沒有過濾得到改善。當我得到時間的時候會編輯,但是我認爲我會放棄它,因爲它可能會幫助別人。大部分信貸@JarekTkaczyk

$monthsAgo = \Carbon\Carbon::now()->subMonth($months); 

// Query 1: students with a completed report 
$studentsWithCompletedLink = $studentsWithCompletedLink 
    ->whereHas('phdReport.link', function ($query) { 
     $query->where('status', 'complete'); 
    }) 
    ->get(); 

if ($months != 0) { 
    // filter through to get students where the report date_to is more than $months months ago 
    $studentsWithReport = $studentsWithCompletedLink->filter(function ($student) use ($monthsAgo) { 
     return $student->latestReport->date_to <= $monthsAgo; 
    }); 
} 

Student.php

public function latestPhdReport() 
{ 
    return $this->hasOne(\App\Models\PhdReport::class)->latest('date_to'); 
}