如何使用Laravel 4.2批量删除数据库表中不在数组中的行

时间:2015-07-25 14:09:55

标签: php laravel eloquent fluent

我想删除表格中不在数组中的行。在以下示例中,这将批量删除与$ cards_to_delete对应的行。

$cards_to_delete = array(1, 2, 3);
Collection::where('username', '=', $username)
    ->whereIn('id', $cards_to_delete)
    ->delete();

我怎样才能删除数组中不存在的所有内容?这些方面的东西:

$cards_to_keep = array(1, 2, 3);
Collection::where('username', '=', $username)
    ->whereIn('id', '!=', $cards_to_keep)
    ->delete();

1 个答案:

答案 0 :(得分:4)

Laravel也提供->whereNotIn()方法:

$cards_to_keep = array(1, 2, 3);
Collection::where('username', '=', $username)
    ->whereNotIn('id', $cards_to_keep)
    ->delete();