Skip to content
Advertisement

Is there effective way in laravel to select records from database and set them user_id?

I have to make laravel application that use database 100k+ records. I have table with columns: numer, date, segment, user_id.

I am selecting records that I need with:

$datetime = new DateTime();
$datetime->modify('+6 months');

$seg = "biz";

$select = DB::table('clients')
            ->where('user_id', $id)
            ->where('date','<',$datetime)
            ->where('segment',$seg)
            ->get();

I get some records and now, Is there anyway set user_id for like 100 of records from select?

Main rule is I cannot sort dates in database.

Advertisement

Answer

You could mass-update the rows after selecting a given amount of rows to be updated:

$datetime = new DateTime();
$datetime->modify('+6 months');

$seg = "biz";

$new_id = 743; // <-------- example of value to be updated

$updated_rows = DB::table('clients')
                  ->where('user_id', $id)
                  ->where('date','<', $datetime)
                  ->where('segment', $seg)
                  ->take(100)                       // <---- # records to be updated
                  ->update(['user_id' => $new_id]); // <---- new value(s) to update

Check the documentation related to this topic (it is oriented to Eloquent, but also applies for Laravel Query Builder).

PS: $updated_rows is the number of rows that has been updated.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement