M
M
microf2014-09-07 15:16:33
MySQL
microf, 2014-09-07 15:16:33

How to display categories?

Good afternoon. A very simple question, so to speak, the basics of the basics, but something I'm stupid.
There are two tables
Category
| id | parent_id | name
and
Articles
| id | title | cat_id |
cat_id associated with category.id
I need to display all categories and articles on one page without any clicks, ie. Heading1
Subheading1 Article1 Article2
Subheading2 Article3 Article4 Heading2 .... As I understand it, I need to get several arrays with categories, subcategories and articles in the controller in order to transfer them to view / index and display foreach there as well. How to do it?
public function actionArticle() {
$cats = Category::find()->all();
foreach ($cats as $c => $cat) {
And here's my problem
} }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Andreevich, 2014-09-07
@reffy

To be honest, I didn't understand your question. What else is a heading, subheading, etc.
If you need to display a list of categories and a list of articles (in which order was not specified), then get a list of categories and a list of articles, and then output:

// контроллер
public function actionArticle() {
    $categories = Category::find->all();
    $articles = Articles::find->all();

    return $this->render('article', [
        'categories' => $categories,
        'articles' => $articles
    ]);
}

// вьюха article.php
<?php
foreach ($categories as $category) {
    echo $category->name;
}

foreach ($articles as $article) {
    echo $article->name;
    echo $article->someone;
    echo $article->id;
}

Maybe somewhere I made a mistake in the code, I'm writing from the tablet right here.

P
Pavel Volintsev, 2014-09-07
@copist

1. In the controller, select all categories from the database, arrange their hierarchy in memory, and transfer to the view. And in the view, display the categories + their articles, using the relationships described in the models
Documentation about the organization of relations between models in Yii
(!) But this is only suitable for a small amount of data, because otherwise you will need memory to sort the categories + separate SQL queries to search for articles for each category.
2. For a large amount of data, the implementation of the hierarchy through parent-child should be abandoned in favor of nested sets . Implementation of nested set for Yii (didn't check its correctness, but fork 51 speaks for itself ;) )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question