Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57670

MVC Complex query and model usage

I have 3 tables.

They have one-to-many relations. User have many campaigns. Campaign has many links.

I calculate top users by counting the total number of links each user have. So I join 3 tables and group by user and select user and sum(links).

This query involves 3 tables. I have already 3 model class for each of these tables. Now my question is in which model should I put this query? should it go in User model (as I call it top10users? Or there is other way to get this info by utilizing already existing 3 models. I want to know what is most suitable from MVC's point of view.

Additional Information

I am using in .

Query:

SELECT u.id, 
       u.name, 
       SUM(l.num_visited) total_num_visited 
FROM   users u 
       JOIN campaigns c 
         ON ( u.id = c.user_id ) 
       JOIN links l 
         ON ( c.id = l.campaign_id ) 
GROUP  BY u.id 
ORDER  BY total_num_visited DESC 
LIMIT  10;

Upvotes: 1

Views: 794

Answers (2)

pauld
pauld

Reputation: 241

There's no strict reason that your model absolutely has to map 1-to-1 with a table. It may make the most sense in this case to provide a model specifically for Top Users, especially because it is dependent on joining data from several related tables.

Then if there is specific business logic related to Top Users that isn't relevant to the standard User class, you can keep it separated and clean. You can always provide helper / factory methods from TopUser that return instances of User, Campaign, or Link if you need to drill down.

Upvotes: 4

floriank
floriank

Reputation: 25698

I would say go for topusers(). There is no "correct" answer to this question, not in a technical context. But it should be clearly to understand. So if you want to get top users, why would you put such a method in one of the other models than users? Think of a new team member who gets your code: Where would you look for top users when not in the users model first?

Upvotes: 1

Related Questions