【发布时间】:2016-04-25 00:05:43
【问题描述】:
我需要显示带有总 cmets 的提要,以及对该提要的总点赞数以及发表评论的用户的详细信息。
Feed 表
| id | movie_id | user_id | description |
|----|----------|----------|-------------|
| 1 | 1 | 1 | Lorem Ipsum |
评论表
| id | feed_id | user_id | comment |
|----|-------- |----------|-----------|
| 1 | 1 | 2 | comment 1 |
| 2 | 1 | 3 | comment 2 |
点赞表
| id | feed_id | user_id |
|----|-------- |----------|
| 1 | 1 | 2 |
| 2 | 1 | 3 |
用户表
| id | username| email |
|----|-------- |--------|
| 1 | a | a@a.com|
| 2 | b | b@b.com|
| 3 | c | c@c.com|
关系
Feed.php
public function user () {
return $this->belongsTo('App\User');
}
public function likes () {
return $this->hasMany('App\Like');
}
public function comments () {
return $this->hasMany('App\Comment');
}
User.php
public function feeds () {
return $this->belongsToMany('App\Feed');
}
public function like () {
return $this->belongsTo('App\Like');
}
public function comment () {
return $this->belongsTo('App\Comment');
}
Like.php
public function user () {
return $this->belongsTo('App\User');
}
public function feed () {
return $this->belongsTo('App\Feed');
}
Comment.php
public function user () {
return $this->belongsTo('App\User');
}
public function feed () {
return $this->belongsTo('App\Feed');
}
现在我需要获取所有提要(我已经完成了这个),包括 cmets 计数、喜欢计数以及发表评论的用户详细信息。
我可以使用 Eloquent 在单个查询中得到它吗?
【问题讨论】:
-
你不能在单个查询中使用 eloquent.. 但你可以在 4 个查询中做到这一点
-
我正在为移动 API 工作,如果我使用 4 个查询会太慢
-
它可能比使用连接的 1 个长查询更快。如果您想使用连接,则可以轻松测试它,而不是在这里查看:laravel.com/docs/5.1/queries#joins
-
你能显示你的控制器代码来获取计数吗?
标签: php mysql eloquent laravel-5.1 relationship