views:

143

answers:

3

Hello

Is it bad habit to work with multiple models in one controller action? Should it always be like one controller-one model-one view?

+4  A: 

No, of course its not a bad habit. Where you work with multiple tables, then various models will be needed.

The problem is not so much with this, but with the frameworks ability to handle advanced queries, joins and filtering based on these models. It's one of those bugbears when you are "obliged" to follow a framework's particular aesthetic about database interaction, but this depends on, of course, which framework and how far you are relying on magic behaviours.

Not every project is a simple blog! :)

edit: I should say also, that this kind of thing is one of my main gripes with MVC frameworks in general. The compromise between what your project is attempting to achieve, and what the framework allows is always going to be where the hair is lost and the late nights invested..

danp
Thanks for the rapid answer!
PPPHP
In my opinion the majority of your code should be in your models, of which there will be many classes. Definitely not a one-to-one mapping between models and controllers. That would be a bad thing.
d11wtq
Yep, everyone loves fat models :)
danp
I concur with this answer, but I just want to point out that table != model.
troelskn
haha this helped me a lot!!what a great forum this is!
PPPHP
Dont forget to push accept (click on the tick) if this helped out :)
danp
First I did it like this that the controller only had one model so I had to instantiate other models inside the main model so that I could work with multiple models. It gained a bit hierarcihical. :P So it is possible to instantiate multiple models inside a controller action and they dont have to have anything related to each other..
PPPHP
+1  A: 

I couldn't imagine being able to only work with one model at a time. Those databases are called 'relational databases' for a reason. All the tables interact with each other.

I actually used a framework that only allowed loading of the one model that was associated with that controller. Definitely a horrible experience, the only operations that worked were basic CRUD actions.

Lotus Notes
Thanks for the rapid answer!
PPPHP
A: 

Like everyone else is saying, you're free to do what you want. I'd suggest looking at the site for the framework you are using, and see how other people are using it. They often have "Projects using XXXX Framework" there.

And like troelskin's comment, 1 table does not always equal one model. Some of the examples using a basic Active Record pattern (like CodeIgniter) tend to go with the 1 table 1 model method.

Ian