Home > Enterprise >  Randomly select multiple rows and randomly update multiple rows between 2 tables (Laravel eloquent)
Randomly select multiple rows and randomly update multiple rows between 2 tables (Laravel eloquent)

Time:06-08

I have a situation like this My mysql has 2 tables product_queue and description I want to randomize multiple rows of content of column 'content' in descripton table to randomly update multiple rows into 'descripton' column of product_queue table provided that store_id column of 2 tables must be equal

Image description table

Image Product_queue table

I tried this code but it didn't

$descriptions = DescriptionModel::orderByRaw("RAND()")->get();
foreach ($descriptions as $description) {
      ProductQueue::where('store_id', $description->store_id)
      ->update(['description' => $description->content]);
}

Before I ask a question, I have also tried on the forum

CodePudding user response:

use this to get random records from db $data = DB::table('table_name')->inRandomOrder()->limit(50)->get();

CodePudding user response:

Try this:

 $descriptions = DescriptionModel::inRandomOrder()->get();
 $descriptions = DescriptionModel::inRandomOrder()->limit(20)->get(); // get 20 random records 

or:

 $descriptions = DescriptionModel::all()->random(); 
 $descriptions = DescriptionModel::all()->random(20); // get 20 random records
  • Related