Wahyu Kusuma
Wahyu Kusuma

Reputation: 23

Laravel model get all results, but if model has relation then check for certain condition

Assume I have book models and borrow models. They are one-to-many relationships. I want to get a collection of all the books but return the result if the book is borrowed within the current week. But if it's not, then don't display. I've been trying whereHas(), but I think it didn't suit what I'm looking for.

$displayed_books = Books::orderBy('updated_at', 'DESC')
    ->ifHasborrow('borrow', function ($query) {
        $query->where('start_date', '>=', currentweek())
            ->where('end_date', "<=", currentweek());
    })

Upvotes: 1

Views: 299

Answers (1)

lin
lin

Reputation: 18392

$displayedBooks = Books::orderBy('updated_at', 'DESC')
    ->where(function ($query) {
        $query->whereHas('borrow', function($query) {
            $now = Carbon::now();
            $query->where([
                ['start_date', '>=', $now->startOfWeek()],
                ['end_date', '<=', $now->endOfWeek()]
            ]);
        $query->orWhereDoesntHave('borrow');
    })
})->get();

Upvotes: 1

Related Questions