我有两个表,posts
和likes
。我需要创建一个查询使用Eloquent ,它会获取特定user_id
所喜欢的所有帖子。
换句话说,它应该是这样的:
SELECT * FROM posts p LEFT JOIN likes l ON p.id = l.post_id WHERE l.user_id = 2 ORDER BY l.created_at DESC
posts
表:
+----+---------+------------+-------------+
| id | user_id | message | created_at |
+----+---------+------------+-------------+
| 1 | 2 | Hello! | <SOME TIME> |
| 2 | 3 | World! | <SOME TIME> |
| 3 | 2 | Something. | <SOME TIME> |
| 4 | 2 | Another. | <SOME TIME> |
+----+---------+------------+-------------+
likes
表:
+----+---------+---------+-------------+
| id | post_id | user_id | created_at |
+----+---------+---------+-------------+
| 1 | 1 | 2 | <SOME TIME> |
| 2 | 2 | 2 | <SOME TIME> |
| 3 | 1 | 3 | <SOME TIME> |
| 4 | 3 | 2 | <SOME TIME> |
+----+---------+---------+-------------+
这是我的Post
课程:
<?php
class Post extends Eloquent {
protected $table = 'posts';
public function likes()
{
return $this->hasMany('Like');
}
}
Like
类:
<?php
class Like extends Eloquent {
protected $table = 'likes';
public function post()
{
return $this->belongsTo('Post');
}
}
我该怎么做?
答案 0 :(得分:9)
这应该有效:
$user_id = //however you get the userid here.
$posts = Post::whereHas('likes', function ($q) use($user_id){
$q->where('user_id', $user_id);
})->get();
答案 1 :(得分:0)
您可以使用Laravel的DB类在两个或多个表上执行连接,以下是您在laravel中执行查询的方式:
$users = DB::table('posts')
->leftJoin('likes', 'posts.id', '=', 'likes.post_id')
->select('posts.*', 'likes.*')
->where('likes.user_id', '=', '2')
->orderBy('likes.created_at', 'desc')
->get();
不要忘记在控制器顶部使用DB类;
如果你想以雄辩的方式做到这一点,你应该做下面的事情:
$result = Post::whereHas('likes', function ($q) use($user_id)
{
$q->where('user_id', $user_id);
})
->orderBy('likes.created_at')
->get();