$price = Price::find('all', array('select' => 'avg(weight) as price'))->price;
Thank shafiq.rst khan ! ))))
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] =>
)
)
use foreach or just
$price = Price::find(array('select' => 'avg(weight) as price'))->price;
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)
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
)
)
How to show only the result:
[avg(weight)] => 7.0000
Thank!