Multiplication withCount / SQL query with calculation on named/created columnarithmetic operations in query builder laravelCalculating value differences between two records in EloquentHow to find all the tables in MySQL with specific column names in them?How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?How do I specify unique constraint for multiple columns in MySQL?MySQL query to get column names?SQL select only rows with max value on a columnSQL query return data from multiple tableswhere query from table with column foreign keyLaravel, pimpable. filter request by nullLaravel - Unit Testing with SoftDeletesHow write pivot table with name of column in whereBetween condition?
Why is vowel phonology represented in a trapezoid instead of a square?
How to handle professionally if colleagues has referred his relative and asking to take easy while taking interview
Given 0s on Assignments with suspected and dismissed cheating?
Have there been any examples of re-usable rockets in the past?
Why didn't Daenerys' advisers suggest assassinating Cersei?
How does this piece of code determine array size without using sizeof( )?
Capital gains on stocks sold to take initial investment off the table
bash: Counting characters within multiple files
Is it standard for US-based universities to consider the ethnicity of an applicant during PhD admissions?
I recently started my machine learning PhD and I have absolutely no idea what I'm doing
A person lacking money who shows off a lot
Why use a retrograde orbit?
What are the effects of eating many Goodberry per day?
Why is the marginal distribution/marginal probability described as "marginal"?
Who is frowning in the sentence "Daisy looked at Tom frowning"?
Is it standard to have the first week's pay indefinitely withheld?
Why would you put your input amplifier in front of your filtering for and ECG signal?
Deleting the same lines from a list
Physically unpleasant work environment
refer string as a field API name
FIFO data structure in pure C
Why are there five extra turns in tournament Magic?
What is this rubber on gear cables
Polynomial division: Is this trick obvious?
Multiplication withCount / SQL query with calculation on named/created column
arithmetic operations in query builder laravelCalculating value differences between two records in EloquentHow to find all the tables in MySQL with specific column names in them?How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?How do I specify unique constraint for multiple columns in MySQL?MySQL query to get column names?SQL select only rows with max value on a columnSQL query return data from multiple tableswhere query from table with column foreign keyLaravel, pimpable. filter request by nullLaravel - Unit Testing with SoftDeletesHow write pivot table with name of column in whereBetween condition?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
Arithmetic calculations on created columns?
How does one do arithmetic calculations (e.g. sum product) on calculated columns that do not yet exist in DB? E.g. if you have a model claims and it belongsToMany passengers (passengers technically stored as users).
Neither model will keep a count of how many passengers there is per claim, the value is stored in a pivot table claim_user.
I aim targeting to do an SQL calculation along the line of $valuePerPassenger = claims.value / passengers_count where conditions of join are met.
Target query
$query = Claim::query();
$query->addSelect('id' , 'commission');
$query->withCount('passengers', 'poasSigned');
$query->addSelect(DB::raw(sum('claims.commission / passengers_count * poas_signed_count as expectedClaimValue');
$result = $query->get;
// $result = $query->sum('expectedClaimValue'); <-- Bonus if this works
Please note that Laravel generates passengers_count and poas_signed_count (i.e. powers_of_attorney_signed) and attaches to the eloquent record via the withCount method. But they do not exist before the query.
Error message: Column not found: 1054
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'claims.commission / passengers_count * poas_signed_count' in 'field list' (SQL: select `claims`.*, (select count(*) from `users` inner join `claim_user` on `users`.`id` = `claim_user`.`user_id` where `claims`.`id` = `claim_user`.`claim_id` and `users`.`deleted_at` is null) as `passengers_count`, (select count(*) from `powers_of_attorney` where `claims`.`id` = `powers_of_attorney`.`claim_id` and `powers_of_attorney`.`deleted_at` is null) as `poas_count`, `id`, `commission`, (select count(*) from `users` inner join `claim_user` on `users`.`id` = `claim_user`.`user_id` where `claims`.`id` = `claim_user`.`claim_id` and `users`.`deleted_at` is null) as `passengers_count`, (select count(*) from `powers_of_attorney` where `claims`.`id` = `powers_of_attorney`.`claim_id` and `status` = closed and `powers_of_attorney`.`deleted_at` is null) as `poas_signed_count`, `claims`.`commission / passengers_count * poas_signed_count` as `expectedClaimValue` from `claims` where `claims`.`deleted_at` is null)
Workaround
Created a workaround using chunk and looping through the records as such:
Claim::select('id', 'commission')
->withCount('passengers', 'poasSigned')
->chunk(100, function ($claims) use (&$data)
foreach ($claims as $claim)
$data['expectedClaimValue'] += $claim->commission / $claim->passengers_count * $claim->poas_signed_count;
);
But obviously that workaround is much slower as it relies on creating collections to calculate the results. I am hoping to do this straight in MySQL query.
I have found many answers (e.g. arithmetic operations in query builder laravel) on how to do the raw query if the columns already exist on the related model/ DB record. But in case the column is a calculation based on pivot/relationship - how does one make that work with DB::raw?
Thank you for the help!
Claim Model
DB structure
-id
-commission
-...
public function passengers()
return $this->belongsToMany('AppUser');
public function poas()
return $this->hasMany('AppPOA', 'claim_id', 'id');
public function poasSigned()
return $this->poas()->signed();
protected function getPassengersCountAttribute($value)
return $value ?? $this->passengers_count = $this->passengers()->count();
protected function getPoasCountAttribute($value)
return $value ?? $this->poas_count = $this->poas()->count();
protected function getPoasSignedCountAttribute($value)
return $value ?? $this->poasSigned_count = $this->poasSigned()->count();
User Model
DB structure
-id
-name
-...
Passenger Model (table = 'claim_user')
DB structure
-id
-claim_id
-user_id
PowersOfAttorney Model
DB structure
-id
-status
-claim_id
-user_id
public function claim()
return $this->belongsTo('AppClaim', 'claim_id', 'id');
public function user()
return $this->belongsTo('AppUser', 'user_id', 'id');
public function scopeSigned($query)
return $query->where('status', '=', 'closed');
public function getSignedAttribute()
// Verify POA signed (closed) AND not deleted
return $this->status == 'closed' && $this->deleted_at == null;
php mysql laravel
add a comment |
Arithmetic calculations on created columns?
How does one do arithmetic calculations (e.g. sum product) on calculated columns that do not yet exist in DB? E.g. if you have a model claims and it belongsToMany passengers (passengers technically stored as users).
Neither model will keep a count of how many passengers there is per claim, the value is stored in a pivot table claim_user.
I aim targeting to do an SQL calculation along the line of $valuePerPassenger = claims.value / passengers_count where conditions of join are met.
Target query
$query = Claim::query();
$query->addSelect('id' , 'commission');
$query->withCount('passengers', 'poasSigned');
$query->addSelect(DB::raw(sum('claims.commission / passengers_count * poas_signed_count as expectedClaimValue');
$result = $query->get;
// $result = $query->sum('expectedClaimValue'); <-- Bonus if this works
Please note that Laravel generates passengers_count and poas_signed_count (i.e. powers_of_attorney_signed) and attaches to the eloquent record via the withCount method. But they do not exist before the query.
Error message: Column not found: 1054
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'claims.commission / passengers_count * poas_signed_count' in 'field list' (SQL: select `claims`.*, (select count(*) from `users` inner join `claim_user` on `users`.`id` = `claim_user`.`user_id` where `claims`.`id` = `claim_user`.`claim_id` and `users`.`deleted_at` is null) as `passengers_count`, (select count(*) from `powers_of_attorney` where `claims`.`id` = `powers_of_attorney`.`claim_id` and `powers_of_attorney`.`deleted_at` is null) as `poas_count`, `id`, `commission`, (select count(*) from `users` inner join `claim_user` on `users`.`id` = `claim_user`.`user_id` where `claims`.`id` = `claim_user`.`claim_id` and `users`.`deleted_at` is null) as `passengers_count`, (select count(*) from `powers_of_attorney` where `claims`.`id` = `powers_of_attorney`.`claim_id` and `status` = closed and `powers_of_attorney`.`deleted_at` is null) as `poas_signed_count`, `claims`.`commission / passengers_count * poas_signed_count` as `expectedClaimValue` from `claims` where `claims`.`deleted_at` is null)
Workaround
Created a workaround using chunk and looping through the records as such:
Claim::select('id', 'commission')
->withCount('passengers', 'poasSigned')
->chunk(100, function ($claims) use (&$data)
foreach ($claims as $claim)
$data['expectedClaimValue'] += $claim->commission / $claim->passengers_count * $claim->poas_signed_count;
);
But obviously that workaround is much slower as it relies on creating collections to calculate the results. I am hoping to do this straight in MySQL query.
I have found many answers (e.g. arithmetic operations in query builder laravel) on how to do the raw query if the columns already exist on the related model/ DB record. But in case the column is a calculation based on pivot/relationship - how does one make that work with DB::raw?
Thank you for the help!
Claim Model
DB structure
-id
-commission
-...
public function passengers()
return $this->belongsToMany('AppUser');
public function poas()
return $this->hasMany('AppPOA', 'claim_id', 'id');
public function poasSigned()
return $this->poas()->signed();
protected function getPassengersCountAttribute($value)
return $value ?? $this->passengers_count = $this->passengers()->count();
protected function getPoasCountAttribute($value)
return $value ?? $this->poas_count = $this->poas()->count();
protected function getPoasSignedCountAttribute($value)
return $value ?? $this->poasSigned_count = $this->poasSigned()->count();
User Model
DB structure
-id
-name
-...
Passenger Model (table = 'claim_user')
DB structure
-id
-claim_id
-user_id
PowersOfAttorney Model
DB structure
-id
-status
-claim_id
-user_id
public function claim()
return $this->belongsTo('AppClaim', 'claim_id', 'id');
public function user()
return $this->belongsTo('AppUser', 'user_id', 'id');
public function scopeSigned($query)
return $query->where('status', '=', 'closed');
public function getSignedAttribute()
// Verify POA signed (closed) AND not deleted
return $this->status == 'closed' && $this->deleted_at == null;
php mysql laravel
"that workaround is much slower" - How much? Did you measure it? Or just assuming? How many rows are you fetching?
– Paul Spiegel
Mar 23 at 17:29
Have not done extensive testing. But doing a calculation with chunks for 5k records takes about 60 seconds. Doing a calculation in SQL directly takes less than a second. That said, I have only been able to do sums in SQL, not sum products - but presume timing is still way faster than creating collections I do not really need. Any ideas on how to solve the arithmetics on a calculated (or named) column?
– Peder Wessel
Mar 23 at 21:11
1
When dealing with thousands of rows, you shouldn't use eloquent at all. My test here shows that most time is taken by fetching rows into eloquent models and accessing eloquent attributes - not by calculations. So try thegetQuery()"trick" to fetch rows intostdClassobjects. Then make the calculations in a loop.
– Paul Spiegel
Mar 24 at 1:16
Worked like a charm. Learnt something completely new today - amazing feeling - thank you!
– Peder Wessel
Mar 24 at 4:45
add a comment |
Arithmetic calculations on created columns?
How does one do arithmetic calculations (e.g. sum product) on calculated columns that do not yet exist in DB? E.g. if you have a model claims and it belongsToMany passengers (passengers technically stored as users).
Neither model will keep a count of how many passengers there is per claim, the value is stored in a pivot table claim_user.
I aim targeting to do an SQL calculation along the line of $valuePerPassenger = claims.value / passengers_count where conditions of join are met.
Target query
$query = Claim::query();
$query->addSelect('id' , 'commission');
$query->withCount('passengers', 'poasSigned');
$query->addSelect(DB::raw(sum('claims.commission / passengers_count * poas_signed_count as expectedClaimValue');
$result = $query->get;
// $result = $query->sum('expectedClaimValue'); <-- Bonus if this works
Please note that Laravel generates passengers_count and poas_signed_count (i.e. powers_of_attorney_signed) and attaches to the eloquent record via the withCount method. But they do not exist before the query.
Error message: Column not found: 1054
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'claims.commission / passengers_count * poas_signed_count' in 'field list' (SQL: select `claims`.*, (select count(*) from `users` inner join `claim_user` on `users`.`id` = `claim_user`.`user_id` where `claims`.`id` = `claim_user`.`claim_id` and `users`.`deleted_at` is null) as `passengers_count`, (select count(*) from `powers_of_attorney` where `claims`.`id` = `powers_of_attorney`.`claim_id` and `powers_of_attorney`.`deleted_at` is null) as `poas_count`, `id`, `commission`, (select count(*) from `users` inner join `claim_user` on `users`.`id` = `claim_user`.`user_id` where `claims`.`id` = `claim_user`.`claim_id` and `users`.`deleted_at` is null) as `passengers_count`, (select count(*) from `powers_of_attorney` where `claims`.`id` = `powers_of_attorney`.`claim_id` and `status` = closed and `powers_of_attorney`.`deleted_at` is null) as `poas_signed_count`, `claims`.`commission / passengers_count * poas_signed_count` as `expectedClaimValue` from `claims` where `claims`.`deleted_at` is null)
Workaround
Created a workaround using chunk and looping through the records as such:
Claim::select('id', 'commission')
->withCount('passengers', 'poasSigned')
->chunk(100, function ($claims) use (&$data)
foreach ($claims as $claim)
$data['expectedClaimValue'] += $claim->commission / $claim->passengers_count * $claim->poas_signed_count;
);
But obviously that workaround is much slower as it relies on creating collections to calculate the results. I am hoping to do this straight in MySQL query.
I have found many answers (e.g. arithmetic operations in query builder laravel) on how to do the raw query if the columns already exist on the related model/ DB record. But in case the column is a calculation based on pivot/relationship - how does one make that work with DB::raw?
Thank you for the help!
Claim Model
DB structure
-id
-commission
-...
public function passengers()
return $this->belongsToMany('AppUser');
public function poas()
return $this->hasMany('AppPOA', 'claim_id', 'id');
public function poasSigned()
return $this->poas()->signed();
protected function getPassengersCountAttribute($value)
return $value ?? $this->passengers_count = $this->passengers()->count();
protected function getPoasCountAttribute($value)
return $value ?? $this->poas_count = $this->poas()->count();
protected function getPoasSignedCountAttribute($value)
return $value ?? $this->poasSigned_count = $this->poasSigned()->count();
User Model
DB structure
-id
-name
-...
Passenger Model (table = 'claim_user')
DB structure
-id
-claim_id
-user_id
PowersOfAttorney Model
DB structure
-id
-status
-claim_id
-user_id
public function claim()
return $this->belongsTo('AppClaim', 'claim_id', 'id');
public function user()
return $this->belongsTo('AppUser', 'user_id', 'id');
public function scopeSigned($query)
return $query->where('status', '=', 'closed');
public function getSignedAttribute()
// Verify POA signed (closed) AND not deleted
return $this->status == 'closed' && $this->deleted_at == null;
php mysql laravel
Arithmetic calculations on created columns?
How does one do arithmetic calculations (e.g. sum product) on calculated columns that do not yet exist in DB? E.g. if you have a model claims and it belongsToMany passengers (passengers technically stored as users).
Neither model will keep a count of how many passengers there is per claim, the value is stored in a pivot table claim_user.
I aim targeting to do an SQL calculation along the line of $valuePerPassenger = claims.value / passengers_count where conditions of join are met.
Target query
$query = Claim::query();
$query->addSelect('id' , 'commission');
$query->withCount('passengers', 'poasSigned');
$query->addSelect(DB::raw(sum('claims.commission / passengers_count * poas_signed_count as expectedClaimValue');
$result = $query->get;
// $result = $query->sum('expectedClaimValue'); <-- Bonus if this works
Please note that Laravel generates passengers_count and poas_signed_count (i.e. powers_of_attorney_signed) and attaches to the eloquent record via the withCount method. But they do not exist before the query.
Error message: Column not found: 1054
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'claims.commission / passengers_count * poas_signed_count' in 'field list' (SQL: select `claims`.*, (select count(*) from `users` inner join `claim_user` on `users`.`id` = `claim_user`.`user_id` where `claims`.`id` = `claim_user`.`claim_id` and `users`.`deleted_at` is null) as `passengers_count`, (select count(*) from `powers_of_attorney` where `claims`.`id` = `powers_of_attorney`.`claim_id` and `powers_of_attorney`.`deleted_at` is null) as `poas_count`, `id`, `commission`, (select count(*) from `users` inner join `claim_user` on `users`.`id` = `claim_user`.`user_id` where `claims`.`id` = `claim_user`.`claim_id` and `users`.`deleted_at` is null) as `passengers_count`, (select count(*) from `powers_of_attorney` where `claims`.`id` = `powers_of_attorney`.`claim_id` and `status` = closed and `powers_of_attorney`.`deleted_at` is null) as `poas_signed_count`, `claims`.`commission / passengers_count * poas_signed_count` as `expectedClaimValue` from `claims` where `claims`.`deleted_at` is null)
Workaround
Created a workaround using chunk and looping through the records as such:
Claim::select('id', 'commission')
->withCount('passengers', 'poasSigned')
->chunk(100, function ($claims) use (&$data)
foreach ($claims as $claim)
$data['expectedClaimValue'] += $claim->commission / $claim->passengers_count * $claim->poas_signed_count;
);
But obviously that workaround is much slower as it relies on creating collections to calculate the results. I am hoping to do this straight in MySQL query.
I have found many answers (e.g. arithmetic operations in query builder laravel) on how to do the raw query if the columns already exist on the related model/ DB record. But in case the column is a calculation based on pivot/relationship - how does one make that work with DB::raw?
Thank you for the help!
Claim Model
DB structure
-id
-commission
-...
public function passengers()
return $this->belongsToMany('AppUser');
public function poas()
return $this->hasMany('AppPOA', 'claim_id', 'id');
public function poasSigned()
return $this->poas()->signed();
protected function getPassengersCountAttribute($value)
return $value ?? $this->passengers_count = $this->passengers()->count();
protected function getPoasCountAttribute($value)
return $value ?? $this->poas_count = $this->poas()->count();
protected function getPoasSignedCountAttribute($value)
return $value ?? $this->poasSigned_count = $this->poasSigned()->count();
User Model
DB structure
-id
-name
-...
Passenger Model (table = 'claim_user')
DB structure
-id
-claim_id
-user_id
PowersOfAttorney Model
DB structure
-id
-status
-claim_id
-user_id
public function claim()
return $this->belongsTo('AppClaim', 'claim_id', 'id');
public function user()
return $this->belongsTo('AppUser', 'user_id', 'id');
public function scopeSigned($query)
return $query->where('status', '=', 'closed');
public function getSignedAttribute()
// Verify POA signed (closed) AND not deleted
return $this->status == 'closed' && $this->deleted_at == null;
php mysql laravel
php mysql laravel
edited Mar 23 at 21:13
Peder Wessel
asked Mar 23 at 16:20
Peder WesselPeder Wessel
3121415
3121415
"that workaround is much slower" - How much? Did you measure it? Or just assuming? How many rows are you fetching?
– Paul Spiegel
Mar 23 at 17:29
Have not done extensive testing. But doing a calculation with chunks for 5k records takes about 60 seconds. Doing a calculation in SQL directly takes less than a second. That said, I have only been able to do sums in SQL, not sum products - but presume timing is still way faster than creating collections I do not really need. Any ideas on how to solve the arithmetics on a calculated (or named) column?
– Peder Wessel
Mar 23 at 21:11
1
When dealing with thousands of rows, you shouldn't use eloquent at all. My test here shows that most time is taken by fetching rows into eloquent models and accessing eloquent attributes - not by calculations. So try thegetQuery()"trick" to fetch rows intostdClassobjects. Then make the calculations in a loop.
– Paul Spiegel
Mar 24 at 1:16
Worked like a charm. Learnt something completely new today - amazing feeling - thank you!
– Peder Wessel
Mar 24 at 4:45
add a comment |
"that workaround is much slower" - How much? Did you measure it? Or just assuming? How many rows are you fetching?
– Paul Spiegel
Mar 23 at 17:29
Have not done extensive testing. But doing a calculation with chunks for 5k records takes about 60 seconds. Doing a calculation in SQL directly takes less than a second. That said, I have only been able to do sums in SQL, not sum products - but presume timing is still way faster than creating collections I do not really need. Any ideas on how to solve the arithmetics on a calculated (or named) column?
– Peder Wessel
Mar 23 at 21:11
1
When dealing with thousands of rows, you shouldn't use eloquent at all. My test here shows that most time is taken by fetching rows into eloquent models and accessing eloquent attributes - not by calculations. So try thegetQuery()"trick" to fetch rows intostdClassobjects. Then make the calculations in a loop.
– Paul Spiegel
Mar 24 at 1:16
Worked like a charm. Learnt something completely new today - amazing feeling - thank you!
– Peder Wessel
Mar 24 at 4:45
"that workaround is much slower" - How much? Did you measure it? Or just assuming? How many rows are you fetching?
– Paul Spiegel
Mar 23 at 17:29
"that workaround is much slower" - How much? Did you measure it? Or just assuming? How many rows are you fetching?
– Paul Spiegel
Mar 23 at 17:29
Have not done extensive testing. But doing a calculation with chunks for 5k records takes about 60 seconds. Doing a calculation in SQL directly takes less than a second. That said, I have only been able to do sums in SQL, not sum products - but presume timing is still way faster than creating collections I do not really need. Any ideas on how to solve the arithmetics on a calculated (or named) column?
– Peder Wessel
Mar 23 at 21:11
Have not done extensive testing. But doing a calculation with chunks for 5k records takes about 60 seconds. Doing a calculation in SQL directly takes less than a second. That said, I have only been able to do sums in SQL, not sum products - but presume timing is still way faster than creating collections I do not really need. Any ideas on how to solve the arithmetics on a calculated (or named) column?
– Peder Wessel
Mar 23 at 21:11
1
1
When dealing with thousands of rows, you shouldn't use eloquent at all. My test here shows that most time is taken by fetching rows into eloquent models and accessing eloquent attributes - not by calculations. So try the
getQuery() "trick" to fetch rows into stdClass objects. Then make the calculations in a loop.– Paul Spiegel
Mar 24 at 1:16
When dealing with thousands of rows, you shouldn't use eloquent at all. My test here shows that most time is taken by fetching rows into eloquent models and accessing eloquent attributes - not by calculations. So try the
getQuery() "trick" to fetch rows into stdClass objects. Then make the calculations in a loop.– Paul Spiegel
Mar 24 at 1:16
Worked like a charm. Learnt something completely new today - amazing feeling - thank you!
– Peder Wessel
Mar 24 at 4:45
Worked like a charm. Learnt something completely new today - amazing feeling - thank you!
– Peder Wessel
Mar 24 at 4:45
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55315829%2fmultiplication-withcount-sql-query-with-calculation-on-named-created-column%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55315829%2fmultiplication-withcount-sql-query-with-calculation-on-named-created-column%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
"that workaround is much slower" - How much? Did you measure it? Or just assuming? How many rows are you fetching?
– Paul Spiegel
Mar 23 at 17:29
Have not done extensive testing. But doing a calculation with chunks for 5k records takes about 60 seconds. Doing a calculation in SQL directly takes less than a second. That said, I have only been able to do sums in SQL, not sum products - but presume timing is still way faster than creating collections I do not really need. Any ideas on how to solve the arithmetics on a calculated (or named) column?
– Peder Wessel
Mar 23 at 21:11
1
When dealing with thousands of rows, you shouldn't use eloquent at all. My test here shows that most time is taken by fetching rows into eloquent models and accessing eloquent attributes - not by calculations. So try the
getQuery()"trick" to fetch rows intostdClassobjects. Then make the calculations in a loop.– Paul Spiegel
Mar 24 at 1:16
Worked like a charm. Learnt something completely new today - amazing feeling - thank you!
– Peder Wessel
Mar 24 at 4:45