【问题标题】:Eloquent query where column is in another table雄辩的查询列在另一个表中
【发布时间】:2015-09-28 16:57:24
【问题描述】:

我有两张桌子,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

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> |
+----+---------+---------+-------------+

这是我的Postclass:

<?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');
    }

}

我该怎么做?

【问题讨论】:

  • 你为什么不直接使用 laravel 关系呢?设置用户 喜欢关系?

标签: php laravel laravel-5 eloquent laravel-4


【解决方案1】:

您可以使用 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 类;

如果你想用 eloquent 做到这一点,你应该这样做:

$result = Post::whereHas('likes', function ($q) use($user_id)
                {
                   $q->where('user_id', $user_id);
                })
                  ->orderBy('likes.created_at')
                  ->get();

【讨论】:

  • 正如问题所说,我需要使用 Eloquent。
  • 他需要逆向,Posts 而不是 Likes
【解决方案2】:

这应该可行:

$userId = //however you get the userid here.

$posts = Post::whereHas('likes', function ($q) use ($userId) {
    $q->where('user_id', $user_id);
})->get();

【讨论】:

  • (I am writing this on my mobile in the train so apologize any typos),没问题,为你编辑,Posts 假设是Post :-)
  • 帮我解决了类似的问题
猜你喜欢
  • 2018-07-01
  • 2019-06-22
  • 2021-05-02
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 2015-07-07
  • 2018-01-26
  • 2014-04-12
相关资源
最近更新 更多