N
N
Nikita Kravchenko2019-06-13 17:10:45
Laravel
Nikita Kravchenko, 2019-06-13 17:10:45

How to display number of comments in laravel?

Hello! (I'm new to this area)
Task: display the last 100 news on the page, signing how many positive and how many negative comments each has. And also sorting them by the ratio of positive / negative, whoever has a higher ratio, those are higher.
Question: how to display at least just the number of comments for each news item separately (positive/negative)?
I think it's a little silly to make a separate request for counting comments for each news item. Considering that there are an average of 1000 of them (yes, yes). And every time the user enters, it is too resource intensive.

public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id'); // Идентификатор комментария
            $table->integer('status'); // Статус комментария (0 - отрицательный,
                                       // 1 - положительный, 2 - нейтральный, null - не указано)
            $table->text('text'); // Текст комментария
            $table->integer('news_id')->unsigned();
            $table->timestamps();
        });
    }

This is a table with comments. With the news, everything is simple, there is an ID and the actual text of the news with a title.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konata Izumi, 2019-06-13
@nkdev55

$news = News::withCount(['comments as comments_positive' => function ($query) {
    $query->where('status', 1);
},'comments as comments_neutral' => function ($query) {
    $query->where('status', 0);
},])->get();

// счетчики для первой новости из выборки
$news[0]->comments_positive_count;
$news[0]->comments_neutral_count;

We will receive all the news with a counter of positive and neutral comments.
Ps need relay comments in News model

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question