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()
任何建議,將不勝感激!
這將做http://softonsofa.com/querying-relations-in-laravel-get-models-where-latest-相關 - 是/ –
@JarekTkaczyk感謝您的鏈接。我現在有一個工作解決方案,但它肯定需要一些微調。一旦我滿意,我會發佈一個答案。再次感謝您的幫助 - 非常感謝。 – haakym
很酷。完成後分享您的代碼。 –