Laravel在whereIn子句中的限制

时间:2019-04-12 12:43:41

标签: php laravel postgresql eloquent

我正在使用laravel 5.7

我有whereIn子句的查询

在我的控制器中,我有这样的查询:

$post = Post::whereIn('reply_from_id', [1,2])
            ->orderBy('created_at', 'desc')->get();

我得到这样的输出:

[
    {
        "id": 3,
        "title": "test reply id 2",
        "reply_from_id": 2
    },
    {
        "id": 4,
        "title": "test reply id 1",
        "reply_from_id": 1
    },
    {
        "id": 5,
        "title": "test reply id 1 again",
        "reply_from_id": 1
    },
    {
        "id": 6,
        "title": "test reply id 1 again and again",
        "reply_from_id": 1
    },
    {
        "id": 7,
        "title": "test reply id 2 again",
        "reply_from_id": 2
    }
]

我想限制输出,每个ID仅显示2个数据

例如:

[
    {
        "id": 3,
        "title": "test reply id 2",
        "reply_from_id": 2
    },
    {
        "id": 4,
        "title": "test reply id 1",
        "reply_from_id": 1
    },
    {
        "id": 5,
        "title": "test reply id 1 again",
        "reply_from_id": 1
    },
    {
        "id": 7,
        "title": "test reply id 2 again",
        "reply_from_id": 2
    },

]

我尝试像这样使用take()

$post = Post::whereIn('reply_from_id', [1,2])
            ->take(2)
            ->orderBy('created_at', 'desc')->get();

但这只是显示这样的数据

[
    {
        "id": 3,
        "title": "test reply id 2",
        "reply_from_id": 2
    },
    {
        "id": 4,
        "title": "test reply id 1",
        "reply_from_id": 1
    }
]

如何在whereIn子句中限制数据?

2 个答案:

答案 0 :(得分:2)

您可以按reply_from_id分组以获取每个ID的1条记录

使用use关键字将变量绑定到函数的作用域中。

关闭可能会从父范围继承变量。任何此类变量都必须在函数标头中声明[使用]。

$everyHow = 3;
$ids      = [1,2];
$post     = Post::whereIn("posts.id", function ($query) use ($everyHow, $ids) {
    $query->select("p.id")->from('posts p')
    ->whereRaw('p.id = posts.id')
    ->whereIn("p.reply_from_id", $ids)
    ->orderBy("p.id", "desc")->limit($everyHow);
})->get();

编辑

说明:考虑到id是主键并正确记录数据,每个reply_from_id必须有3条记录才能标识并提取查询,因此,我认为id是清楚吗?

答案 1 :(得分:0)

$post = Post::whereIn('reply_from_id', [1,2])
            ->limit(1)
            ->orderBy('created_at', 'desc')->get();
$post = Post::whereIn('reply_from_id', [1,2])
            ->limit(1)
            ->orderBy('created_at', 'desc')->first();