质疑雄辩的关系

时间:2015-12-02 10:24:53

标签: php laravel orm eloquent

我在我的雄辩模型/ db中有以下关系集:

fig, ax = plt.subplots() im = ax.imshow(np.random.random((10,10))) cb = fig.colorbar(im) cb.formatter.set_powerlimits((0, 0)) cb.ax.yaxis.set_offset_position('left') cb.update_ticks() plt.show() 有很多Student

PhdReport有一个PhdReport

我需要获得Link s(单个)最新Student(属性PhdReport)超过6个月且date_to连接到LinkPhdReport'完整'。

我正在尝试使用雄辩的关系来做这件事,而且我对查询关系的概念很陌生,所以我想知道是否有更好的方法来处理我正在采取的问题。

到目前为止,这是相关的代码:

PhdReport.php

status

Student.php

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

到目前为止,这是我最好的拍摄,但我不确定第一个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

如果我跑:

$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();

非常感谢任何建议!

1 个答案:

答案 0 :(得分: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');
}