Sunday, July 25, 2010

COUNT between two Models

Hi everybody, I have 2 models: Restaurant and Zone


app/models/restaurant.php
<?php
class Restaurante extends AppModel {

var $name = 'Restaurant';

var $belongsTo = array(
'Zone' => array(
'className' => 'Zone',
'foreignKey' => 'zone_id'
)

);

}
?>

app/models/zone.php
<?php
class Zone extends AppModel {
var $name = 'Zone';

var $hasMany = array(
'Restaurant' => array(
'className' => 'Restaurant',
'foreignKey' => 'zone_id'
)
);

}
?>


And I need to execute this query:

SELECT restaurants.zone_id, zones.title, COUNT(restaurants.zone_id) AS
zonecounter
FROM restaurants, zones
WHERE restaurants.sector_id = zones.id
GROUP BY restaurants.sector_id
ORDER BY zones.nombre ASC

So, T wrote the next function at my Restaurant controller

app/controllers/restaurant_controller.php
<?php
class RestaurantsController extends AppController {

var $name = 'Restaurants';
var $uses = array('Restaurants', 'Zones');

function index() {
$this->set('zones', $this->Zone->Restaurant->find('all',
array(
'fields' => array('Restaurant.zone_id', 'Zone.title',
'COUNT(Restaurant.zone_id) AS zonecounter'),
'conditions' => array('Restaurant.city_id' => 4),
'order' => array('Zone.title ASC'),
'group' => array('Restaurant.zone_id')
)

)
);
}
?>

*PS: At 'conditions' I need a value for Restaurant.city_id, because
I'm using this function for more cities.

Then, in my index view, to show the results that I have

app/views/restaurants/index.ctp

<div>
<h2>Zones</h2>
<ul>
<?php foreach ($zones as $zone): ?>
<li><?php echo $html->link($zone['Zone']['title'], '#');?></li>
<?php endforeach; ?>
</ul>
</div>


It shows me something like

Ex:
Zones
- Zone 1
- Zone 2
- zone 3
- Zone 4

Shows me only the zones where are restaurants. Cool.

But also I need to show the value of "zonecounter" in order to
display how many restaurants are in every zone:

Ex:
Zones
- Zone 1 (22)
- Zone 2 (31)
- zone 3 (16)
- Zone 4 (24)

Some ideas?

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate