Welcome Guest, Not a member yet? Register   Sign In
Best practice selecting data from related models
#1

I'm trying to figure out what is the best practice with selecting data from related model.

I have a model (and a db table) "person" and then i have a model (and a db table) comment. There may be multiple comments for one person and commend has "person_id" column.

I have two cases in particular.

First i need to show persons profile with all his comments.
In my controller do I select the needed person through my person model and then select all the comments through my comments model? Or is it more correct for person model already return person with all comments?
I myself would guess that first option is ok.

Second case is where i need to show all latest comments with name of the person who made the comment.
So in my controller is it correct to select all latest comments from comments model and then select a person for each or them? Or is it more correct for the comments model to return comment with person name included?
In this case i would guess that second option is better. It seems really strange to first select comments and then iterate them and select a person for each of them.

So im kind of confused because case 1 and 2  seem similar but i would use different solutions for them. Which seems right to you guys?
Reply
#2

I agree with your intuition that person should not provide or manage comments. The comments model in both cases would be your primary domain of interest. If you are being terribly oop then your $this->comments->get_latest() would return a list of comment objects, each one encapsulating its author. If you want to display the author you might say: (for each comment to be displayed) $author = $comment->author(); echo $author->nick_name(). Or bending the law of demeter (foreach comment) $comment->author()->nick_name(). Then you can decide in your view whether to display the person's first and last name or nick_name, or status_level, etc. But if you are dealing with tens of thousands (millions?) of comments you may say nuts to oop and have the get_latest() method return an array of the results of the join of comments and people tables where date greater than...
Reply
#3

use base model
Reply




Theme © iAndrew 2016 - Forum software by © MyBB