I
I
Ivan2021-10-07 19:57:46
Laravel
Ivan, 2021-10-07 19:57:46

Laravel how to correctly compose a database query?

I have two tables.
One is the history of purchases, the second is the history of payments.

The payment history table has a buy_id column - this is the id from the purchase history table.
I need to make sure that I can take data from the purchase history and immediately with one request and payment history.

It will become clearer when you see:

BuyHistory::whereDate('buy_history.created_at', date('Y-m-d', strtotime($day)))
            ->where('status', 'success')
            ->join('history_payments', 'buy_history.id', '=', 'history_payments.buy_id')
            ->sum('amount');


But it does not work, for some reason it captures many different extra days at once (if you remove ->join, then everything is fine, but then there is no amount column). The amount column is in the history_payments table.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2021-10-07
@youmixx

HistoryPayments whereHas BuyHistory (hasOne relation) where (status date queries) sum amount

V
Vyacheslav Plisko, 2021-10-07
@AmdY

If you use the sum aggregate function, then you are expected to group records by some groupBy field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question