Laravel:删除所有不在数组中的记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29510716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel : Delete all records that are not in array
提问by Clément Rigo
I have a datepicker calendar in my views, and basically I need to synchronize the selected dates (that I send in ajax) with a BoxDeliveryDate model (which only has one column named "date").
我的视图中有一个日期选择器日历,基本上我需要将所选日期(我在 ajax 中发送)与 BoxDeliveryDate 模型(只有一列名为“date”)同步。
So in my Controller I was able to write a pretty nice method to only create a new record if one the selected dates is not yet stored in the database, like this :
因此,在我的控制器中,我能够编写一个非常好的方法来仅在所选日期尚未存储在数据库中的情况下创建一个新记录,如下所示:
foreach (Request::get('dates') as $date) {
$date_formated = date('Y-m-d', strtotime($date));
BoxDeliveryDate::firstOrCreate(['date'=>$date_formated]);
}
Now, if the user de-select one the dates in the datepicker, later, and synchronize, I need to delete it from the database.
现在,如果用户取消选择日期选择器中的日期,稍后再同步,我需要将其从数据库中删除。
Is there a nice way to do that in Laravel ? In other words, to delete every record of the table that are NOT in my Request::get('dates')
?
在 Laravel 中是否有一个很好的方法来做到这一点?换句话说,要删除不在我的表中的每条记录Request::get('dates')
?
Also, I searched for a simple way to synchronize everything with only one method, but couldn't find anything.
此外,我搜索了一种简单的方法来仅使用一种方法同步所有内容,但找不到任何内容。
Thanks for helping !
感谢您的帮助!
回答by lukasgeiter
You can use whereNotIn()
for that:
你可以使用whereNotIn()
:
BoxDeliveryDate::whereNotIn('date', Request::get('dates'))->delete();
Note that this will not trigger any model events nor will it work with soft delete. Also, depending on the format of dates
you might have to format the array before passing it to whereNotIn()
.
请注意,这不会触发任何模型事件,也不会与软删除一起使用。此外,根据dates
您的格式,您可能必须在将数组传递给whereNotIn()
.
Also I believe it should be Request::input('dates')
but it's possible that both actually works...
我也相信它应该是,Request::input('dates')
但有可能两者实际上都有效......
回答by Matt Hiscock
I would highly recommend using the soft delete trait (built into Laravel) if your doing mass deletes!
如果您进行批量删除,我强烈建议您使用软删除特性(内置于 Laravel 中)!