I am trying to delete any five rows from my users table. I used following code for that.
DB::table('users')->take(5)->delete();
But it deletes all rows in that table. How will I overcome this problem?
I am trying to delete any five rows from my users table. I used following code for that.
DB::table('users')->take(5)->delete();
But it deletes all rows in that table. How will I overcome this problem?
You said you want to delete 5 rows randomly, in this case this will work, I've tested it:
DB::table('users')->whereIn('id', DB::table('users')->orderBy(DB::raw("RAND()"))->take(5)->lists('id'))->delete();
It will take 5 random IDs and then will delete rows with these IDs with just two queries:
select `id` from `users` order by RAND() asc limit 5
delete from `users` where `id` in ('786', '186', '82', '578', '232')
You can use rand() function and delete users this way
DB::table('users')->DB::table('users')->orderby(RAND())->take(5)->delete();
You can use foreach
$users = DB::table("users")->orderBy(DB::raw("RAND()"))->take(5)->get();
foreach($users as $user){
DB::table("users")->where("id", $user->id)->delete();
}
DB::table('users')->whereIn('id', DB::table('users')->take(5)->lists('id'))->delete();