Answer the question
In order to leave comments, you need to log in
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();
});
}
Answer the question
In order to leave comments, you need to log in
$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;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question