简体   繁体   中英

inside laravel insert query i want to implement a for loop over the array to insert multiple records in one go

what i want to achieve is that inside the DB query i insert all the records in one go so that the query doesn't run many times. the following code doesn't allow me to use the for loop inside the array. kindly help.

if($user=="MasterDealer")
        {
            if($request['accessibleTodealers']!='' || $request['accessibleTodealers']!=null)
            {
                $memberships=explode(",",$request['accessibleTodealers']);
                $membe = array();
                $now = Carbon::now();
                DB::table('accessible_membership_logs')->insert([
                    array(
                        for ($i=0; $i <count($memberships) ; $i++){
                        array(
                            ['membership_id']=$memberships[$i],
                            ['masterdealer_id']=$dealer,
                            ['dealer_id'] = null,
                            ['user'] = 'masterdealer',
                            ['operation'] = 'Accessible',
                            ['admin_id'] = $data['id'],
                            ['created_at'] = $now->format('Y-m-d H:i:s'),
                            ['updated_at'] = $now->format('Y-m-d H:i:s')
                        )}
                    )
                ]);
                Alert::message("","Changes Updated.!","success");
                return redirect()->intended('/admin/masterDealerDetail/'.$dealer); 
            }
        }

Do the loop before insert query

$array = array();

for ($i=0; $i <count($memberships) ; $i++){
    $array[] = array(
        'membership_id' => $memberships[$i],
        'masterdealer_id' => $dealer,
        'dealer_id' => null,
        'user' => 'masterdealer',
        'operation' => 'Accessible',
        'admin_id' => $data['id'],
        'created_at' => $now->format('Y-m-d H:i:s'),
        'updated_at' => $now->format('Y-m-d H:i:s')
    );
}

DB::table('accessible_membership_logs')->insert($array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM