0

I have a customer model with many transactions, and I need to get customers only where the customer's latest transaction is < 5 years from now. So the result was a customer who had any transaction that matched the condition. Even the transaction that matched the condition is not the latest one.

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();
Karl Hill
  • 12,937
  • 5
  • 58
  • 95

1 Answers1

0

i resolved the problem by combining whereHas and whereDoesntHave like below:

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