Raj Polinovsky Fri Jul 12 06:41:11 -0400 2013

Subject: How to show the AVG() result of the query.

Hi!
Tell me, how to show the AVG result of the query.

I have query:
$price = Price::find('all', array('select' => 'avg(weight)'));
print_r($price);
Result:
Array
(
[0] => Comments Object
(
[errors] =>
[attributes:ActiveRecord\Model:private] => Array
(
[avg(weight)] => 7.0000
)

[__dirty:ActiveRecord\Model:private] => Array
(
)
[__readonly:ActiveRecord\Model:private] => 
[__relationships:ActiveRecord\Model:private] => Array
(
)
[__new_record:ActiveRecord\Model:private] => 
)

)

How to show only the result:
[avg(weight)] => 7.0000

Thank!


shafiq.rst khan Tue Jul 16 00:55:47 -0400 2013

$price = Price::find('all', array('select' => 'avg(weight) as price'))->price;

Raj Polinovsky Tue Jul 16 00:57:37 -0400 2013

Thank shafiq.rst khan ! ))))

Raj Polinovsky Tue Jul 16 01:38:12 -0400 2013

Sorry, but now displays an error: Notice: Trying to get property of non-object in ...

print_r($price);
Array
(
[0] => Comments Object
(
[errors] =>
[attributes:ActiveRecord\Model:private] => Array
(
[price] => 7.0000
)

[__dirty:ActiveRecord\Model:private] => Array
(
)
[__readonly:ActiveRecord\Model:private] => 
[__relationships:ActiveRecord\Model:private] => Array
(
)
[__new_record:ActiveRecord\Model:private] => 
)

)

shafiq.rst khan Tue Jul 16 04:29:04 -0400 2013

use foreach or just
$price = Price::find(array('select' => 'avg(weight) as price'))->price;

Megan McVey Thu Jul 18 18:43:22 -0400 2013

What shafiq.rst khan wrote works because of this:

The earlier version, using find('all', array(...)) returns an array of results, with the one you want in the first element.

You could either foreach over the array (all one element of it), or you could grab the first element:

$prices = Price::find('all', array(...));
$price_value = $prices[0]->price;

Or you could change to using find('first', array(...)) which is the default, so you can write it as find(array(...)):

$price = Price::find(array(...));
$price_value = $price->price;

Note that in BOTH cases, we assume the return of at least one result line. Since this is doing an average, there should always be exactly one result, so that is fine.

Note also that you might want a group-by clause to the find to ensure the right results.

The KEY point here is that the "all" or "first" in the find(whatever, ...) call doesn't affect which rows the query will average, just which rows of the result (the average) that the query will return.

(1-5/5)