繁体   English   中英

Laravel在whereIn子句中的限制

[英]Laravel limit in whereIn clause

我正在使用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子句中限制数据?

您可以按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 ,其中清楚吗?

$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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM