0
votes

I wrote this code to add multiple clients and users to my database:

$oConnection = \Propel::getConnection();
    $oConnection->beginTransaction();
    for ( $i = 1; $i <= 4; $i++ )
    {
        $oClient = new Client();
        $aData   = array(
            'companyname' => 'company' . $i,
            'contactname' => 'contact' . $i,
            'mail'        => 'mail' . $i . '@hotmail.com',
            'phone'       => '12345678',
            'active'      => true
        );
        $oClient->fromArray($aData, \BasePeer::TYPE_FIELDNAME);
        $oClient->save($oConnection);
        for ( $i = 1; $i <= 4; $i++ )
        {
            $oUser = new User();
            $aData = array(
                'client_id' => $oClient->getId(),
                'firstname'    => 'firstname' . $i,
                'lastname'     => 'lastname' . $i,
                'mail'         => 'mail' . $i . '@hotmail.com',
            );
            $oUser->fromArray($aData, \BasePeer::TYPE_FIELDNAME);
            $oUser->save($oConnection);
        }
    }
    $oConnection->commit();

Somehow this only creates one client with four users affected to him not four clients with four users for each one.

1

1 Answers

1
votes

Seems like you are using same variable for both FOR-s. Change your code to:

$oConnection = \Propel::getConnection();
$oConnection->beginTransaction();
for ( $i = 1; $i <= 4; $i++ )
{
    $oClient = new Client();
    $aData   = array(
        'companyname' => 'company' . $i,
        'contactname' => 'contact' . $i,
        'mail'        => 'mail' . $i . '@hotmail.com',
        'phone'       => '12345678',
        'active'      => true
    );
    $oClient->fromArray($aData, \BasePeer::TYPE_FIELDNAME);
    $oClient->save($oConnection);
    for ( $j = 1; $j <= 4; $j++ ) // changed
    {
        $oUser = new User();
        $aData = array(
            'client_id' => $oClient->getId(),
            'firstname'    => 'firstname' . $j, // changed
            'lastname'     => 'lastname' . $j, // changed
            'mail'         => 'mail' . $j . '@hotmail.com', // changed
        );
        $oUser->fromArray($aData, \BasePeer::TYPE_FIELDNAME);
        $oUser->save($oConnection);
    }
}
$oConnection->commit();