G
G
Governor2020-05-16 20:08:44
Laravel
Governor, 2020-05-16 20:08:44

How to use models?

While learning Laravel, and MVC in general, I'm making a blog site that has a footprint. tables:

  • articles - articles
  • article_tags - association of tags with an article
  • tags - tags
  • comments - comments

5ec019aa036ce701283495.png

The main page needs to display many articles and each of them has a list of tags.
I have no experience with models and at first I made all calls to the database in the controller through requests.
The selection looks like this:
return DB::select(
            'SELECT a.`id`, a.`Title`, a.`Text`, a.`create_at`, 
            
            (SELECT GROUP_CONCAT(\'<a href="/tag/\', t.id, \'">\', t.`name`, \'</a>\' SEPARATOR \'\') 
            FROM article_tags _t 
            INNER JOIN tags t ON _t.tag_id = t.id WHERE _t.article_id = a.id) AS `tags`
             
            FROM articles AS a 
            LIMIT '.($curPage-1)*$articlesOnPage.', '.$articlesOnPage);


But after all, the essence of MVC is about the separation of logic, and especially accessing the database through models , so my solution is not kosher, and everything must be transferred to the models.

Further, I don’t understand how to create models correctly:
1) For each articles , you will need to get a list of tags, do you need to create a model of the article_tags table , because this table is just a binder, or add a getMyTags type method in the articles table model in which to describe the same query?

2) It will be difficult for me to describe the request using the methods of the models or the request constructor, it is easier for me to write the request manually. Is it necessary to use special methods in models?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Perin, 2020-05-17
@Mr-Governor

1) Article, Tag, Comment models.
For the Article model, links with tags and comments, read about links here
. For article_tags, the model is not needed, and it’s better to call article_tag, it’s more correct, in the laravel style, for example, more details here
2) Not necessarily, but this is the framework’s goodies. Models make simple requests much faster, more elegant than manually.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question