Sum of all the columns of a rows in Laravel - php

How can I find out the sum of certain columns of a row in MySQL using Laravel?
I know ->sum('something'); gives you the sum of a column. But what about a row?
Is there any method to do so in Laravel?
Currently I'm adding each column values manually and getting the sum.

There is no built-in way to do this, but you can write a function yourself. Well, actually, I did that already for you! ;)
You have two options. The boring one, a function that just returns a predefined sum:
public function getSum(){
return $this->value1 + $this->value2; // and so on
}
Or a generic function that you can place inside a BaseModel and use in every class and with every attributes you want:
public function getAttributeSum(){
$sum = 0;
foreach(func_get_args() as $attribute){
$sum += $this->getAttribute($attribute);
}
return $sum;
}
And you call it like this:
$model->getAttributeSum('value1', 'value2');

Just create a model function and pass all the variables to it and do the calculation there. Then return the total and print wherever you want it.
{{Classmodel::total($yourvariablearray)}}
In the Classmodel.php you will have something like:
public static function total($variablearray){
return $total = $variablearray->columnone + $variablearray->columntwo;
}
This should work.

How about this
return \DB::table('table_name')->sum('column_to_be_calculated');
Works for laravel 5 .

Related

Yii2 Framework Relation with Sum Not Working Correctly

I am having an issue when trying to sum related data from another table.
I have created a getter as follows...
public function getContItems()
{
return $this->hasMany(ContItems::className(), ['CONTNO' => 'inspQuoteNo'])->sum('LINETOT');
}
When i use this i get the following error: "frontend\models\Quotes has no relation named "contItems"."
When I declare the getter as follows i get no error but dont want to loop through the results for the sum as its very slow to do this:
public function getContItems()
{
return $this->hasMany(ContItems::className(), ['CONTNO' => 'inspQuoteNo']);
}
Does anyone have any idea why the sum is not working and coming as if there is no relation declared with the sum?
Thanks!
The problem is that a relation should return an object \yii\db\ActiveQuery. If you append ->sum(...) to the query it will return an integer.
But you can use the query returned by the relation like follows:
$sum = $quote->getContItems()->sum('LINETOT');

Why application hungs when using 'count' keyword as localScope function name

I have class Reservation in php Laravel 5.
I create localScope query.
When i use special word count, which is aggregate for sum in scope function name, my application hang up.
When i change function name to something not like keyword like total, everything works fine.
Why application hangs when i use special keyword ? How does process works. Stackoverflow ?
class Reservation extends Model
{
public function scopecount($query){
return $query->count();
}
}
I return it as:
$count = Reservation::currentMonth()->count();
My function currentMonth:
public function scopecurrentMonth($query){
return $query->where('date_from','>=', Carbon::now()->startOfMonth())
->where('date_to','<=', Carbon::now()->endOfMonth());
}
So why it hungs?
When i change name count to total:
public function scopetotal($query){
return $query->count();
}
and
$count = Reservation::currentMonth()->total();
everything works fine.
So why it hungs ?
You don't need to add a scope for count(), besides, it's already taken, unless you want to rename count to total?
You can just add ->count() to your queries and it will return an int.

How can a function call itself in PHP?

I am new with Laravel and PHP so I decide to see the core code and try to read it a little, but when I reached this part, I am confused! how does this function works? $this->getAlias($this->aliases[$abstract]); can a function call itself? wouldn't it be looping?
protected function getAlias($abstract)
{
if (! isset($this->aliases[$abstract])) {
return $abstract;
}
return $this->getAlias($this->aliases[$abstract]);
}
thank you
You may want to read about recursive functions.
A recursive function is a function that calls itself
This function takes some argument and checks if it has an alias. If it does, it calls itself again and checks if found alias has an alias etc.
These are called recursive functions... Which means, a function can call itself until the final condition for the expected output is reached.
A simple example for this would be... Multiplication of 2 until the sum reaches 100.
public function multiplication($a, $sum = 0, $times = 0) {
if($sum == 100) {
return $times;
}
$sum += $a;
$times++;
return multiplication($a, $sum, $times);
}
echo multiplication(2);
Output will be
50
In the function written in the question, it is trying to check if all the abstract value passed as param is set for that current class or not.
Hope you are now clear of the concept. :)

Object returning three value instead of one. Laravel

I have used following code:
public function verify($id,$sid)
{
$sfees = sfee::where('student_id', $sid)->first(['mfee_id']);//mfee_id is the column I'm trying to recover
foreach ($sfees as $sfee) {
echo $sfee;
}
The problem is that it is returning three 1. While it was supposed to return only one.
If i echo $sfees before foreach it returns only one value: {"mfee_id":1}.
What is the problem? Can anyone help me?
You are asking for one model, you don't need to try and iterate it, its a single model (object). (first() can return null though, so you should check)
$sfees->mfee_id;
If you just want the value of that column for that one record:
$mfee_id = sfee::where('student_id', $sid)->value('mfee_id');
Laravel 5.2 Docs - Query Builder - Retrieving Results - Retrieving A Single Row / Column From A Table
You should use return statement for returning from function, not echo.
public function verify($id,$sid)
{
$sfees = sfee::where('student_id', $sid)->first(['mfee_id']);//mfee_id is the column I'm trying to recover
return $some_variable;
}
Your problem is that that your trying to itterate over a single model. That's cause that you itterate over attributes and you get odd result the only think that you need is to do like this:
public function verify($id,$sid)
{
$sfees = sfee::where('student_id', $sid)->first(['mfee_id']);//mfee_id
echo $sfees->mfee_id;
}
$sfees in this example is a single model not a collection of models becasuse you've used first to get it.

Decrement function, decrement all the rows in the tables

Im using laravel v3.2.12-4, and I have an problem with the decrement function. Instead of update only one row, this method affects all the rows in the column. Im using Eloquent, and I have a many_to_many relationship.
The code that constains the decrement method is:
foreach ($ids as $id) {
$indicator = Indicator::find($id);
$tags = $indicator->tags()->get();
foreach ($tags as $tag) {
$indicator->tags()->detach($tag->id);
if ($tag->frequency == 1) {
$tag->delete();
} else {
// I have to made this code to fix the problem with decrement function
// But i want to use decrement
$tag->frequency = $tag->frequency - 1;
$tag->save();
// This dosnt work for me.
// $tag->decrement('frequency');
}
}
$indicator->delete();
}
In the model class Indicator i made the relation with this function:
public function tags()
{
return $this->has_many_and_belongs_to('Tag');
}
In the model class Tag i made the relation with this function:
public function indicators()
{
return $this->has_many_and_belongs_to('Indicator');
}
Well, if I made an update to the column this result OK for me, but when If I use the decrement function this affect all the rows and I don't know if this a bug or something with this method.
Thanks.
This is how it's designed. The decrement() method is actually defined on the Query Builder and not on Eloquents builder. What this means is that when you call $tag->decrement('frequency') it's actually falling through to the QB and simply running a query like UPDATE tag SET frequency=frequency - 1. Notice that there's no WHERE clause?
You could still use the decrement() method but you'd have to do it like this.
$tag->where_id($tag->id)->decrement('frequency');
Now you've set the WHERE clause and only that tag will be decremented. Of course, the cleaner solution is what you've got. Or perhaps this.
$tag->frequency--;
Not tested, may throw an error of some sort.

Categories