bcharron
1 year ago

Inserting many records with an association

Posted 1 year ago by bcharron

I am building a CSV importer. I need to save the data into a couple of tables, and associate them together, but I'd like to do this in as few calls as possible.

I have been able to get the primary table data and save it like so:

foreach ( $records as $offset => $record ) { 
    $is_record_empty = $this->_checkForEmptyRecord( $record );
    $is_record_header = $this->_checkForHeaderContent( $record );
    
    // Check if this $record entry is header row, or empty
    // and continue past it because we don't want to process it.
    if( $is_record_empty || $is_record_header ) {
        continue;
    }

    $time_slot = $this->_determineTimeSlot( $record );
    $time_slot_id = $this->_determineTimeSlotID( $time_slot );
    $address = $this->_formatAddress( $record );
    
    $user_id = ( array_key_exists( $record['Technician'], $techs ) ) ? $techs[$record['Technician']] : null;
    $job_count[$user_id] = array_key_exists($user_id, $job_count) ? $job_count[$user_id] + 1 : 0;
    
    $assignments[] = [
        'company' => 'twc',
        'identifier' => $record['Job ID'],
        'user_id' => $user_id,
        'date' => $this->date,
        'time_slot_id' => $time_slot_id,
        'points' => $record['Est Job Duration'] / 5,
        'type' => $record['Job Type'],
        'display_order' => $job_count[$user_id],
        'notified' => $notified_count ? 1 : 0,
        'created_at' => date( 'Y-m-d G:i:s' ),
        'updated_at' => date( 'Y-m-d G:i:s' ),
    ];
}

return $this->assignment->insert($assignments);

I want to associate $address with the assignment, but from what I can find I can't do this with a bulk insert. Is this the case? Would the best option be to save each assignment individually, and create the association with that save?

Please sign in or create an account to participate in this conversation.