查询列在另一个表中的位置

use*_*694 6 laravel laravel-4 laravel-5

我有两张桌子,postslikes.我需要使用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
Run Code Online (Sandbox Code Playgroud)

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> |
+----+---------+------------+-------------+
Run Code Online (Sandbox Code Playgroud)

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> |
+----+---------+---------+-------------+
Run Code Online (Sandbox Code Playgroud)

这是我的Post班级:

<?php

class Post extends Eloquent {

    protected $table = 'posts';

    public function likes()
    {
        return $this->hasMany('Like');
    }

}
Run Code Online (Sandbox Code Playgroud)

Like班级:

<?php

class Like extends Eloquent {

    protected $table = 'likes';


    public function post()
    {
        return $this->belongsTo('Post');
    }

}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Nic*_*ank 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();
Run Code Online (Sandbox Code Playgroud)