【问题标题】:Laravel limit in whereIn clauseLaravel 在 whereIn 子句中的限制
【发布时间】:2019-09-03 05:38:03
【问题描述】:

我使用的是 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子句中如何限制数据?

【问题讨论】:

    标签: php laravel postgresql eloquent


    【解决方案1】:

    您可以按 reply_from_id 分组,为每个 id 获取 1 条记录

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

    闭包可以从父作用域继承变量。任何此类变量都必须在函数头中声明 [使用 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作为主键和3条记录的情况下正确获取数据,每个reply_from_id必须有一个唯一的id来识别和获取查询因此,我取了id,这清楚吗?

    【讨论】:

    • 抱歉,仅获取 1 条记录。在实际情况下,我希望每个 ID 获得 3 条记录。我将编辑我的问题
    • 现在检查我的答案
    • 我收到错误ERROR: missing FROM-clause entry for table "posts"
    • 现在检查我做了一些更改
    • 为什么使用 whereIn id ?我在哪里可以检查 reply_from_id 是否在 1 和 2 中?
    【解决方案2】:
    $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();
    

    【讨论】:

      猜你喜欢
      • 2017-05-19
      • 2014-05-31
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 2021-08-19
      • 2020-05-01
      • 2019-01-22
      相关资源
      最近更新 更多