Anyone who can help me solve my problem on querying available books? I dont want to allow user to borrow book that is already borrowed or not yet returned and book that out of stock based on the number of copies. I have Book model and books table with number_of_copy column, I have BorrowRequest model and borrow_requests tables with details of borrower or user, and I have BorrowRequestItem model and borrow_request_items table with quantity column which is the number of copy borrowed by the user, and returned_at column to trigger if returned or not. Now I want to query the books that is now borrowed by the user and books with stock.
$user = 1; // sample user but it is dynamic
if (!$user) {
return;
}
$availableBooks = AppModelsBook::where('number_of_copy', '>', 0)
->where('is_requestable', true)
->whereNull('deleted_at')
->whereNotIn('id', function ($query) use ($user) {
$query->select('book_id')
->from('borrow_request_items')
->join('borrow_requests', 'borrow_request_items.borrow_request_id', '=', 'borrow_requests.id')
->whereColumn('borrow_request_items.book_id', 'books.id')
->where('borrow_requests.borrower_user_id', $user)
->whereIn('borrow_requests.status', ['Pending', 'Approved'])
->whereNull('borrow_request_items.returned_at')
->groupBy('book_id')
->havingRaw('SUM(borrow_request_items.quantity) >= books.number_of_copy');
})
->get()
->pluck('title', 'id')
->all();
return $availableBooks;
Jefferson Sarmiento is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.