开发者

Categories View in CakePHP

Following the intro cakephp tutorial to create a blog, I created a database to view, add/edit/delete busin开发者_开发问答esses. Each business has a state or province associated with it, and I'm wondering how I would go about to generate a page that lists all the States, like /states and a page would be like /states/california and lists all the businesses in california.

Right now I currently just have one page that lists all businesses. Wondering how I would design the model/controller/view and routes to handle this. Can't really find a source online that elaborates on this or I just don't know how to look.


Since you're new to cake,I think it's not a good idea to start from HABTM relationship which is what you need in your question and also the most complicated one.So I assume your models relationship as a easier one :hasMany.E.g as follows:

/*this is  your state model
 *state table in database should like:id,name
 *and business table in database:id,name,state_id
 */
class State extends AppModel
{
    var $name = 'State';
    var $hasMany = array(
        'Business'=>array(
                'className'=>'Business',
                'foreignKey'=>'state_id',
                )
);   //this means a State can hasMany Businesses while a Business only belongs to one State

}

Then make the action in your state controller as this:

 /*in your state controller*/
 function showBusinessesByState($statename)
 {
     if($statename && $thestate = $this->State->findByName($statename))
     {
         $this->set('state',$thestate);//debug $thestate you'll find data you need
     }
     else
     {
         $this->Session->setFlash("something wrong happens!");
     }
 }

Now I think you may handle the view file yourself,with a $state variable to retrieve the data $thestate which also contains a businesses list in it.

Now in the /app/config/routes.php do the routing part:

Router::connect('/states/*',array('controller'=>'states','action' => 'showBusinessesByState'));

After finish that you may get what you need with /states/somestate.When you go through this,you may try to solve this with the best way --hasAndBelongsToMany.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜