Should controller know about model relationships?

Let's take a simple example with these 3 models: Article, User, Tag, with relationships:

Article -> has one Author (User), Article -> has many Tags.

When listing articles I also want to get the author and all the tags for each article.

I can do this 2 ways:

  1. Build the query for finding the articles with the relationships in the controller. In laravel this would look like something like:

    $articles = Article::with(array('author', 'tags'))->where('...')->get();

  2. Create a custom method in the Article model: getArticles, which return exactly the same thing:

    return Article::with(array('author', 'tags'))->where('...')->get();

In the second case all relations and query building is handled by the model.

So, my question is: should the controller know about model relationships, or that should be hidden from it.

Answers


It's better to hide it. Consider a case where you need to do the same somewhere else. If it's in controller, you have to repeat youself. If it's in model, you just call (the same) model method again.


Need Your Help

Jquery button click event not firing

javascript jquery html ajax

seems like a simple issue but the solutions to the other problem don't seem to work from me.

Is MySQL LIMIT applied before or after ORDER BY?

sql mysql sql-order-by limit

Which one comes first when MySQL processes the query?