【发布时间】:2021-08-06 23:51:13
【问题描述】:
注意:我使用的是 Laravel 5.3。
我有一张桌子,comments,看起来像这样:
+====+=========+
| id | message |
+====+=========+
| 1 | Hi |
| 2 | World |
+====+=========+
我有第二张表,comment_stats,它跟踪每条评论的总投票数,如下所示:
+====+============+=======+
| id | comment_id | votes |
+====+============+=======+
| 1 | 1 | 10 |
| 2 | 2 | 0 |
+====+============+=======+
最后,我还有第三张表comment_votes,它记录每个用户对每条评论的投票,如下所示:
+====+============+=========+=========+
| id | comment_id | user_id | type |
+====+============+=========+=========+
| 1 | 1 | 10 | 0 |
| 2 | 1 | 9 | 0 |
| 3 | 1 | 8 | 1 |
| 4 | 1 | 7 | 2 |
| 5 | 1 | 6 | 1 |
| 6 | 1 | 5 | 5 |
| 7 | 1 | 4 | 3 |
| 8 | 1 | 3 | 3 |
| 9 | 1 | 2 | 1 |
| 10 | 1 | 1 | 0 |
+====+============+=========+=========+
如您所见,其他用户 (comment_votes) 可以对每条评论进行投票,总投票数记录在 comment_stats 中。每张投票都有一个type。共有 6 个可能的types (0-5)。
我当前的Comment.php 类看起来像:
class Comment extends Model
{
protected $with = [
'votes', 'stats'
];
public function votes()
{
return $this->hasMany('App\Vote');
}
public function stats()
{
return $this->hasOne('App\Stat');
}
}
我的Stat.php 类看起来像:
class Stat extends Model
{
protected $with = [
'topTypes'
];
public function comment()
{
return $this->belongsTo('App\Comment');
}
public function topTypes()
{
// Need to return an array of the top 3 types here
}
}
我的Vote.php 类看起来像:
class Vote extends Model
{
public function comment()
{
return $this->belongsTo('App\Comment');
}
}
我想检索每条评论的前 3 票 types。所以对于comment_id = 1,输出将是[0, 1, 3](作为一个数组),按这个顺序。 0 出现 3 次,1 出现 3 次,3 出现两次。如果有平局,它应该得到较小的整数type。
我试图让 JSON 最终看起来像这样,以便 top_types 是 stats 的一部分:
{
"id": 1,
"message": "Hi",
"stats": {
"id": 1,
"comment_id": 1,
"votes": 10,
"top_types": [0, 1, 3]
}
}
我怎样才能做到这一点?所有这些关系都让我发疯。
【问题讨论】:
标签: laravel laravel-5 eloquent