Laravel有效地删除X记录的方法是否有重复
我正在尝试编写一个查询,以便能够根据名为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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)