0

i think, In "CakePHP" one model is against each controller but i have multiple functions in single controller and each function represent different page and database table. i.e

public function manage_categories(){}
public function manage_sub_categories(){}

above 2 functions are in Admin Controller but now the issue is how to create model against each function to represent database. each function has unique attributes in database. One thing more either model name should be same to controller name "admin" or this name will be same as functions name. while in normal circumstances model name is same to controller name.

"Users" model name is used against "UsersController" kindly guide me ti resolve above said issue. i tried enough to solve it bot couldn't. Thanks in advance.

floriank
  • 25,546
  • 9
  • 42
  • 66

1 Answers1

1

If you have two database tables it would be logical and best practice in terms of SoC to have two controllers instead of throwing a lot different things that don't belong into the same domain into a single controller.

Sometimes when you just want to use a part of data from an associated model you can access it through the associations:

$this->Model->SubModel->foo();

Also you say you have an admin controller which is a working but not very good approach. Instead CakePHP features prefix routing. So an action accessed like /admin/categories/some_action will route to the CategoriesController some_action() action.

"Users" model name is used against "UsersController"

Is wrong, by convention models should be named singular, not plural. Your UsersController won't find an Users model because it's looking for an User model.

And stay away from Model::query(), use the ORM instead as much as you can.

public function manage_categories(){}
public function manage_sub_categories(){}

Should become:

class CategoriesController extends AppController {
    public function admin_index() { /*...*/ }
}
class SubCategoriesController extends AppController {
    public function admin_index() { /*...*/ }
}

But assuming that sub-categories belong to a category which is the same table I don't see a need for a second model or second controller at all.

floriank
  • 25,546
  • 9
  • 42
  • 66
  • suppose "sports" is a category and cricket, football, hockey, tens, volleyball etc are sub categories for sports. then i assume two different tables should to save categories in one table and sub-categories in other. you don't think so it is good approach to save data in database in this way? – user3623305 Nov 28 '14 at 16:35
  • No, use "parent child" or "nested sets" for that. No need to have two tables for a category tree. Check the CakePHP TreeBehavior as well, it helps implementing tree structures. There is a Categories plugin made by the CakeDC available as well. – floriank Nov 28 '14 at 17:10