我有两个表:food(id,name),review(user_id,food_id,rating)。现在我想加入食物表和评论表,并在名称为avg_rating的食物表中添加虚拟列,这显然会根据评论保存食物的平均评级值。所以我的想法是做这样的事情:
$food = FoodQuery::create()
->filterById(15) // constant for testing purposes only
->leftJoinWithReview()
->withColumn("AVG(review.rating)", "avg_rating")
->groupBy("review.rating")
->find()
现在在调试器中我看到了:
result = {Propel\Runtime\Collection\ObjectCollection} [7]
index = {array} [1]
indexSplHash = {array} [1]
model = "Food"
fullyQualifiedModel = \Food
formatter = {Propel\Runtime\Formatter\ObjectFormatter} [10]
data = {array} [1]
0 = {\Food} [34]
new = false
deleted = false
modifiedColumns = {array} [0]
virtualColumns = {array} [1]
avg_rating = "5.0000"
id = 15
name = "Salát Caesar"
collReviews = {Propel\Runtime\Collection\ObjectCollection} [7]
index = {array} [2]
indexSplHash = {array} [2]
model = "Review"
fullyQualifiedModel = "\Review"
formatter = null
data = {array} [2]
0 = {\Review} [14]
new = false
deleted = false
modifiedColumns = {array} [0]
virtualColumns = {array} [0]
user_id = 1
food_id = 15
rating = 3
aFood = {\Food} [34]
aUser = null
alreadyInSave = false
reviewThumbsUpsScheduledForDeletion = null
1 = {\Review} [14]
new = false
deleted = false
modifiedColumns = {array} [0]
virtualColumns = {array} [0]
user_id = 3
food_id = 15
rating = 5
aFood = {\Food} [34]
aUser = null
alreadyInSave = false
reviewThumbsUpsScheduledForDeletion = null
*Propel\Runtime\Collection\Collection*pluralizer = null
collReviewsPartial = false
alreadyInSave = false
reviewsScheduledForDeletion = null
*Propel\Runtime\Collection\Collecti4
问题是平均评分不正确。在virtualColumns中,您可以看到值为“5.0000”的avg_rating字段。但是当你看起来有点低的时候你可以看到这个食物有2条评论,评分为3和5,所以平均值应为“4.0000”。
问题出在哪里?为什么这不能正常工作?
答案 0 :(得分:0)
您目前正在审核表上进行左连接。左连接将导致返回多行(每次检查一行)。对于返回的每一行,只有一个评论,因此平均值为'将与该行的评论分数相同。按平均值进行分组不会有太大作用,它只会以完全相同的分数对评论进行分组,而这并不是您想要的。
您应该首先按食物ID进行分组。然后,您将能够获得每个食物项目的单行,并获得平均评分。
$food = FoodQuery::create()
->filterById(15) // constant for testing purposes only
->groupById()
->leftJoinWithReview()
->withColumn("AVG(review.rating)", "avg_rating")
->find();