• 0

Find MIN or MAX in cakePHP


Question

Maybe I'm being very stupid right now but I just am not able to find the MIN or MAX value from one of the columns in my Reguarplanets Table.

I was trying this statement:

$this->Regularplanet->find('maxvalue' =>  array ('fields' => array('MIN(Regularplanet.Size)' )));

This was done by looking at this guy's code:

Link

What is 'avg_views' in his?

I'm a complete noob when it comes to CakePHP. :(

Link to comment
https://www.neowin.net/forum/topic/957766-find-min-or-max-in-cakephp/
Share on other sites

4 answers to this question

Recommended Posts

  • 0

Try this:

$this->RegularPlanet->find('first', array('fields' => array('MIN(RegularPlanet.Size) as min_size')));

"avg_views" on the page you linked to is just the name he's assigning to the returned field. In my example above, I'm calling mine "min_size".

Model::find() expects one of the following string values as the first parameter: 'all' / 'first' / 'count' / 'neighbors' / 'list' / 'threaded'. Since we just want to return one row, the "min_size", I go with 'first'.

  • 0

Thanks for the reply! You are always very helpful.

Now, another silly question is how do I actually view this onto my webpage.

I have the code in my controller to be

$this -> set ('minS', 	$this->Regularplanet->find('first' , array ('fields' => array('MIN(Regularplanet.Size) as min_size'  ))));

and I can print the array by writing this code in the view:

<?php  pr ($minS); ?>

But, how do I just get the actual value?

Thank you very much.

  • 0
  On 02/12/2010 at 19:30, careless_monkey said:

Thanks for the reply! You are always very helpful.

Now, another silly question is how do I actually view this onto my webpage.

I have the code in my controller to be

$this -> set ('minS', 	$this->Regularplanet->find('first' , array ('fields' => array('MIN(Regularplanet.Size) as min_size'  ))));

and I can print the array by writing this code in the view:

<?php  pr ($minS); ?>

But, how do I just get the actual value?

Thank you very much.

Using your above code:

echo $minS[0]['min_size'];

However, I'd do something like this instead:

$rs = $this->Regularplanet->find('first' , array ('fields' => array('MIN(Regularplanet.Size) as min_size')));
$this->set('minS', $rs[0]['min_size']);

And in the view:

echo $minS;

Your view shouldn't have to deal with residual complexity from the query. As far as it's concerned, it only wants to print out a min size value. It doesn't care how you're generating it.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.