Dan Hanly
Dan Hanly

Reputation: 7839

CakePHP: Limiting number in a group

I'm creating sort of a game, and I want people to be able build a town.
Each user can only build a limited number of a specific buildings in their town (i.e. only 2 post offices, 1 city hall etc.)
I'm struggling with how to implement this.

I have a UserBuildings table to keep track of the user/building associations, a Buildings table and a User table.

On the form where I add a building to my city, I want to first check the building's limit, and omit it from the list of available buildings if it's been reached. Here's what I have:

$buildings = $this->UserBuildings->Buildings->find('list');
$currents = $this->UserBuildings->find('all', array(
    'conditions'=> array(
        'UserBuildings.user_id'=>$this->Auth->user('id')
    )
));

I can get the limits from the $currents array.

Is there a way, via find and query in which I can add some conditions to my $buildings list to remove any entries with a capacity reached.

Obviously, I can run a compare via a for loop and build a more refined list by checking capacities against number of matching entries in the UserBuildings table, but is there a more elegant method, perhaps using CakePHP's own methods?

Upvotes: 1

Views: 205

Answers (1)

floriank
floriank

Reputation: 25698

Simply count how many buildings of a type an user has. By adding a new building you should already know it's id and other data.

Assuming this is ja join table:

$count = $this->UserBuildings->find('count', array(
    'conditions'=> array(
        'UserBuildings.building_id'=>$buildingId,
        'UserBuildings.user_id'=>$this->Auth->user('id')
    )
));

You can then simply compare the count with your limit for that building. all of that should happen in a model by the way.

Upvotes: 1

Related Questions