一篇文章有多个评论,每个评论都有一个得分列。
将新评论(分数)添加到文章时,我想存储文章中所有评论的平均值。
由于分数存储在每个评论中,因此在这种情况下-
1.将所有评论和新评论的分数相加,然后除以评论数。
2.或者,可以将存储在文章中的评论的平均值乘以(评论数-1),然后加上新评论的分数,然后除以评论数。
我试图在laravel querybuilder中编写代码,所以非常困难。
如何在查询生成器中编码?
预先感谢您的帮助。
MariaDB []> desc articles;
+------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| user_id | int(10) unsigned | NO | MUL | NULL | |
| title | varchar(191) | NO | MUL | NULL | |
| content | text | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| average_score | int(11) | YES | | 0 | |
+------------+------------------+------+-----+---------+----------------+
MariaDB []> desc comments;
+------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| user_id | int(10) unsigned | YES | | NULL | |
| parent_id | int(10) unsigned | YES | | NULL | |
| commentable_type | varchar(255) | NO | | NULL | |
| commentable_id | int(10) unsigned | NO | | NULL | |
| content | text | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| deleted_at | timestamp | YES | | NULL | |
| score | int(11) | YES | | 0 | |
+------------------+------------------+------+-----+---------+----------------+
CommentsController.php
public function store(CommentsRequest $request, Article $article)
{
$comment = $article->comments()->create(array_merge(
$request->all(),
['user_id' => 'Guest']
));
#Here, the average value of comments is stored in $ article
...
}
答案 0 :(得分:0)
您可以使用以下方法计算特定列的平均值:
$avg = Model::avg('column_name');
因此,只需添加一个新注释,然后计算平均注释所属注释的平均值。希望对您有帮助:D
答案 1 :(得分:0)
我建议不要使用avg列。可以用
计算mod <- rpart(df[,1] ~ .,
data = df[, c(2,3)],
method = "class")
mod