Laravel有效地删除X记录的方法是否有重复

发布于 2025-01-26 12:38:14 字数 704 浏览 5 评论 0原文

我正在尝试编写一个查询,以便能够根据名为hash的列找到重复记录,并删除除5个最新记录外的所有记录,我认为我可以使用limit limit 限制记录数量但不确定无需执行多个查询的最佳方法的方法。

例如,如果我的数据库表中有30个条目应用程序,其中hash列是 abc ,那么我想删除25个记录离开离开只剩下5个记录。

如果有6个特定hash的记录,那么我只想删除1个记录,但是,如果有少于5个记录,我不确定如何实现这一目标。

我目前的查询以获取这些记录,我将在其中循环并删除的地方是:

/**
 * Get applications by hash
 */
protected function getDuplicateApplications($hash = '')
{
    return Application::where('hash', $hash)
                      ->orderBy('created_at', 'asc')
                      ->limit(5)
                      ->get();
}

我还需要什么?

I'm trying to write a query to be able to find duplicate records based on a column called hash and remove all but the 5 newest records, I figured I could use the limit method to limit the number of records but aren't sure the best way to do it without performing multiple queries.

For example, if I have 30 entries in my database table of applications where the hash column is ABC, then I want to remove 25 records leaving only 5 records left.

If there's 6 records for a particular hash then I'd only want to remove 1 record, I'm not sure how I would achieve this if there are fewer than 5 records though.

My current query to grab these records where I would loop over and delete is:

/**
 * Get applications by hash
 */
protected function getDuplicateApplications($hash = '')
{
    return Application::where('hash', $hash)
                      ->orderBy('created_at', 'asc')
                      ->limit(5)
                      ->get();
}

What else do I need?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

疯到世界奔溃 2025-02-02 12:38:14
protected function deleteDuplicateApplications($hash = '', $skip = 5)
{
    // First get total count
    $totalCount = Application::where('hash', $hash)->count();

    // Then skip certain amount and take rest and delete it.
    return Application::where('hash', $hash)
                        ->orderBy('created_at', 'desc')
                        ->skip($skip)
                        ->take($totalCount - $skip)
                        ->delete();
}

protected function deleteDuplicateApplications($hash = '', $skip = 5)
{
    // First get total count
    $totalCount = Application::where('hash', $hash)->count();

    // Then skip certain amount and take rest and delete it.
    return Application::where('hash', $hash)
                        ->orderBy('created_at', 'desc')
                        ->skip($skip)
                        ->take($totalCount - $skip)
                        ->delete();
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文