我正在使用lumen和Vuejs,并将我的“喜欢”和“评论”表与我的posts表连接在一起。喜欢没有问题,一切正常。 但是,当我加入评论表时,帖子返回的次数与评论的存在次数相同。
if($request->limit == NULL){
$request->limit = 4;
}
$user_name= $request->username;
$post_id = $request->id;
$user = User::where('username', $user_name)->first();
$post_query = Posts::leftJoin('likes', 'posts.id', '=', 'likes.post_id')
->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
->selectRaw('posts.*, count(likes.post_id) as likes')
->selectRaw('posts.*, comments.comment as comment')
->where('posts.user_id', $user->id)
->groupBy('posts.id')
->groupBy('comments.id')
->orderBy('id', 'desc')
->limit($request->limit)
->get();
return response()->json($post_query);
我的代码输出为:
{
"id": 844,
"user_id": 221,
"content": "Das ist mein aller erster Post :) ",
"created_at": "2019-07-01 09:09:00",
"updated_at": "2019-07-01 09:09:00",
"likes": 1,
"comment": "Das ist der zweite Kommentar"
},
{
"id": 844,
"user_id": 221,
"content": "Das ist mein aller erster Post :) ",
"created_at": "2019-07-01 09:09:00",
"updated_at": "2019-07-01 09:09:00",
"likes": 1,
"comment": "das ist der dritte :) "
}
但是我想做的是:
{
"id": 844,
"user_id": 221,
"content": "Das ist mein aller erster Post :) ",
"created_at": "2019-07-01 09:09:00",
"updated_at": "2019-07-01 09:09:00",
"likes": 1,
"comments": {
{
'username' : 'test',
'comment' : "Das ist der zweite Kommentar",
'created_at': 12312312
},
{
'username' : 'test',
'comment' : "Das ist der dritte :)",
'created_at': 12312312
}
}
}
您对我该怎么做有任何想法吗?
答案 0 :(得分:2)
您可以在定义了relationships的情况下使用Eloquent:
Post.php
class Post extends Model {
public function comments()
{
return $this->hasMany(Comment::class);
}
public function likes()
{
return $this->hasMany(Like::class);
}
}
然后在您的查询中
$posts = Post
::with('comments') // Eager loading the 'comments' relationship
->withCount('likes') // Attaching a 'likes_count' to every Post object
->orderBy('id', 'desc')
->limit($request->limit)
->get(); // executing the query
这将输出如下结果:
{
"id": 844,
"user_id": 221,
"content": "Das ist mein aller erster Post :) ",
"created_at": "2019-07-01 09:09:00",
"updated_at": "2019-07-01 09:09:00",
"likes_count": 1,
"comments": {
{
'username' : 'test',
'comment' : "Das ist der zweite Kommentar",
'created_at': 12312312
},
{
'username' : 'test',
'comment' : "Das ist der dritte :)",
'created_at': 12312312
}
}
}
在文档中检查与此解决方案相关的主题: