【问题标题】:Laravel Eloquent only get parent if latest child created_at < than 5 years from nowLaravel Eloquent 只有在最近的孩子 created_at < 5 年后才获得父母
【发布时间】:2022-01-13 08:53:51
【问题描述】:

我有一个包含许多交易的客户模型,我只需要获取客户最近一次交易时间小于 5 年的客户。所以结果是一个客户有任何符合条件的交易。即使符合条件的交易也不是最新的。

public function lastTransaction()
{
    return $this->hasOne(Transaction::class, 'user_id', 'id')->latest();
}

$customers = Customer::whereHas('lastTransaction', function ($q) {
    $q->whereDate('created_at', '<', Carbon::now()->subYears(5));
})->get();

【问题讨论】:

  • "" 明确一点,那是在未来,对吧?
  • 我的意思是,客户最后一次交易应该是 2015、2014、2013...

标签: php laravel eloquent wherehas


【解决方案1】:

我通过组合 whereHas 和 whereDoesntHave 解决了这个问题,如下所示:

Customer::whereHas('transactions', function ($q) {
        $q->whereDate('created_at', '<=', Carbon::now()->subYears(5));
    })->whereDoesntHave('transactions', function ($q) {
        $q->whereDate('created_at', '>', Carbon::now()->subYears(5));
    })->with('lastTransaction')->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多