Howard
Howard

Reputation: 3758

How to mass delete rows in database table that are NOT in array using Laravel 4.2

I'd like to delete the rows in my table which are not in the array. In the following example, this will mass delete rows that correspond to $cards_to_delete.

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

How can I make it so it deletes everything that is NOT in the array? Something along these lines:

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

Upvotes: 2

Views: 1598

Answers (1)

Ben Claar
Ben Claar

Reputation: 3415

Laravel provides a ->whereNotIn() method as well:

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

Upvotes: 4

Related Questions