@Isherath

Как сделать выборку из БД (три связанные таблицы) на Yii2?

Есть три связанные последовательно таблицы.

Код в экшене:

public function actionIndex()
    {
        $model = ForumSection::find()->with('topics.messages')->asArray()->all();
        
        return $this->render('home', ['model' => $model]);
    }


Он возвращает такой массив:

Array
(
    [0] => Array
        (
            [section_id] => 1
            [section_title] => Проекты домов
            [section_title_translit] => proekty-domov
            [view] => 0
            [topics] => Array
                (
                    [0] => Array
                        (
                            [topic_id] => 1
                            [section] => 1
                            [topic_title] => Проект дома Бари
                            [topic_title_translit] => proekt-doma-bari
                            [author] => 0
                            [date] => 
                            [views] => 150
                            [display] => 1
                            [status] => 0
                            [close] => 0
                            [messages] => Array
                                (
                                    [0] => Array
                                        (
                                            [message_id] => 1
                                            [topic] => 1
                                            [author] => 1
                                            [message] => Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                                            [date] => 22.05.2018 1:15
                                            [likes] => 123
                                            [dislikes] => 23
                                        )

                                    [1] => Array
                                        (
                                            [message_id] => 2
                                            [topic] => 1
                                            [author] => 2
                                            [message] => Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
                                            [date] => 22.05.2018 2:22
                                            [likes] => 32
                                            [dislikes] => 4
                                        )

                                    [2] => Array
                                        (
                                            [message_id] => 4
                                            [topic] => 1
                                            [author] => 2
                                            [message] => Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
                                            [date] => 22.05.2018 2:22
                                            [likes] => 32
                                            [dislikes] => 4
                                        )

                                )

                        )
)


...он большой, я его укоротил по понятным причинам. В общем, я это разбираю foreach'ем чтобы были видны принадлежности топиков к разделам. С этим все нормально, но мне нужно, чтобы в каждом массиве topics добавлялось свойство countMessages, в которое записывалось бы количество сообщений, которые находятся в массиве messages, то есть, сами сообщения не нужны на главной странице, поэтому нужно каким-то образом не выводить их, а вместо этого создать свойство в массиве topics с кол-вом сообщений.

Как надо переписать код, чтобы я получил желаемый результат?
  • Вопрос задан
  • 124 просмотра
Пригласить эксперта
Ответы на вопрос 1
@Mysterion
Не понятно зачем Вы дублируете вопросы.
echo count($model->topics->messages);
А если хотите с методом, то вот так:
public function getTopicMessagesCount() {
    return $this->getTopicMessages()->count();
}

Где функция getTopicMessages - это метод связи hasmany getMessages у Вас.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы