Laravel 8 Sum column of related table - laravel

I have 2 tables, 'Invoice table', and related 'linesInvoice' table.
To simplify it, I will say that the invoice lines table has only the invoice_id field for the relationship and total for the price.
Now, I need to get last invoices, with his totals (totals, is the sum of column 'total' in every line).
I've tried many examples, but none works for me correctly.
Controller:
$lastInvoices = Invoice::latest()
->limit(10)
->with(['invoiceLines'])->get();
Model for relation
public function invoiceLines()
{
return $this->hasMany(InvoiceLines::class, 'invoice_id');
}
The result that I want for example looks like:
[
Invoice_id => 1
total => 500 //Sum of totals in lines of invoice 1
],
[
Invoice_id => 2
total => 300 //Sum of totals in lines of invoice 2
],
I guess I could go through all the invoices and lines in foreachs and make the sum. But I hope it can be done in the same query

You can use withSum method. This method accept the relation method as first argument and column to sum as second argument
$lastInvoices = Invoice::latest()
->limit(10)
->withSum('invoiceLines','your_column_name')
->with(['invoiceLines'])->get();

Laravel 8^
Invoice::with('invoiceLines')->latest()->first()->invoiceLines()->sum('totle');
totle colme table invoiceLines

Related

How do I get both a COUNT() and SUM() LEFT JOIN in Laravel Eloquent?

I'm pretty new to joins so excuse me as I get my head round it! I'm trying to join 2 tables onto a links table.
One table is clicks. I want the SUM of any data in the clicks.clicks column where link_id matches. (ie 2 columns, One with 1 in the column and a second with 4 in the clicks column both for link_id=1 would return 5)
And the second table is suggestions which I want the COUNT of any occurrence of link_id to be displayed (ie 4 rows where link_id=1 would return 4)
I'm using eloquent with 2 left joins for this and have managed to get both working independently, however when I put both together, clicks_sum which is the name of my SUM join goes wildly high (Seeming as if the suggestion_count is interfering with what's going on there)
Here's my code so far for what I'm trying to achieve. I'm loading Link ID 2872719 just to test with. It should return 585 for suggestion_count and 4 for clicks_sum but I am getting totally different results than expected
use App\Models\Link;
use App\Models\Suggestion;
return Link::select(
'links.id',
DB::raw('SUM(clicks.clicks) AS click_sum'),
DB::raw('COUNT(suggestions.link_id) AS suggestion_count'),
)
->leftJoin('clicks', 'clicks.link_id', '=', 'links.id')
->leftJoin('suggestions', 'suggestions.link_id', '=', 'links.id')
->where('links.id', 2872719)
->first();
Returned is the following:
App\Models\Link {#1278
id: 2872719,
click_sum: "2340", // Should be 4
suggestion_count: 585, // The presence of this join appears to affect click_sum
}
Any ideas on where I am going wrong?
All my best!
Rather than having two leftJoin instances in your eloquent query you need to combine the two joins together into one leftJoin.
return Link::select(
'links.id',
// get the count of suggestions for each link
DB::raw('(SELECT COUNT(*) FROM suggestions WHERE suggestions.link_id = links.id) AS suggestion_count'),
DB::raw('SUM(clicks.clicks) AS click_sum'),
)
->leftJoin('clicks', 'clicks.link_id', '=', 'links.id', 'suggestions.link_id', '=', 'links.id')
->where('links.id', 2872719)
->groupBy('links.id')
->first();
This should give you the correct result as below:
#original: array:3 [▼
"id" => 2872719
"suggestion_count" => 586
"click_sum" => "4"
]
When performing two leftJoin as you were previously, the click_sum was being multiplied by the total count of suggestions leading to the inflated number being returned.

How to Compare Two Column as Condition in Eloquent Laravel

I want to compare two column as condition in Eloquent Laravel.
For example:
I have 3 columns, qty_1, qty_2, and price.
I wanto to get product which price under 1000 if column qty_1 and qty_2 are equal.
I have tried these codes but not working:
Product::whereColumn('qty_1','=','qty_2', function($query){
return $query->where('price','<', 1000);
});
How to do that?
Thank you.
Try this :
Product::whereColumn('qty_1','qty_2')
->where('price','<',1000)
->get();

How to get the total number of Rows in a table | Cypress

I have a table with N rows. How can I get the total number of rows present in the table?
I search for a name, and that particular name is in row number X, how can I get the value of that particular row.
You can use .find to solve both of your cases.
To get the table row count:
cy.get("#tableID")
.find("tr")
.then((row) => {
//row.length will give you the row count
cy.log(row.length);
});
To get the value ( index ) of the particular row, you can do something like this.
cy.get("#Table Id")
.find("tr")
.then((rows) => {
rows.toArray().forEach((element) => {
if (element.innerHTML.includes("Your Value")) {
//rows.index(element) will give you the row index
cy.log(rows.index(element));
}
});
});
Additional tip: If you want to select a specific table cell containing a value, you can do this:
cy.get("#customers").find("tr").find("td").contains("Germany");
Note: to get the table row index there can be many other alternative ways. Hope you will figure them out on the go.

Laravel - Advanced Sum Aggregate in Laravel Eloquent

I have this table in mysql:
student_payment : id, student_class(varchar), student_code(varchar), gender(varchar), amount(float), created_at (timestamp)
Model name is is StudentPayment
What I want to achieve is that:
If student_class is JSS1, it checks the amount paid by each gender and place it in the respective column
If student_class is JSS2, it checks the amount paid by each gender and place it in the respective column
If student_class is SSS1, it checks the amount paid by everyone, both male and female
If student_class is SSS2, it checks the amount paid by everyone, both male and female
It sums everything vertically and horizontally
It groups everything by date (created_at)
I have this query in my Controller, but don't know how to continue
$students = DB::table('student_payment')
->select(
'student_class',
'gender',
'amount',
DB::raw('DATE(created_at) as created_date')
)
->orderByRaw('created_at DESC');
The result I want to achieve is as shown below:
How do I complete this query in the controller to achieve this result. Thanks
Following Code will give you grouping of student payment data,
$payments = DB::table('student_payment')->orderBy('created_at', 'DESC')->get();
$data = [];
foreach ($payments as $payment){
if($payment->gender=="male"){
$data[$payment->student_class]['male'][] = $payment->amount;
}elseif($payment->gender=="female"){
$data[$payment->student_class]['female'][] = $payment->amount;
}
}
Now you can calculate the sum of amounts using array_sum function. For example,
If you want to calculate payment of JSS1 class female student then,
array_sum(data['JSS1']['female']);
This will give the sum of payment. You can calculate like this for other as well.

How to get Total Sum of one column after multipling with other column values

take a look at this Database screenshot
There are two different columns, i want to multiply column "Purchase" value with Column "Stock". and then want to Sum of all answers. As per example, first row answer is 6600 and second row answer is 4500, i want total after multiplication and sum.
Tried this code: but getting 0 as result.
$purchase_sum = Stock::All()->sum('purchase' * 'stock');
Using Laravel eloquent method.
Thanks in advance
You can either multiply and sum the values using an SQL query (documentation):
$total = DB::table('stock')->selectRaw('purchase * stock AS total')->sum('total');
Or you can use a reducer on your collection (documentation):
$total = Stock::all()->reduce(function ($total, $item) {
return $total + ($item->purchase * $item->stock);
});

Resources