使用Propel强制数据库刷新

Here is an example of my tables

<table name="user">
  <column name="name" type="varchar" size="255" required="true" />
</table>

<table name="environment">
  <column name="user_id" type="integer" size="11" required="true" />
  <column name="insertion_time" type="timestamp" required="true" phpName="InsertionTime" />

  <foreign-key foreignTable="user" phpName="User">
    <reference local="user_id" foreign="id"/>
  </foreign-key>
</table>

I want to insert some environment linked with their user.

function insertEnvironment($id) {
    $user = findUser($id);

    $env = new Environment();
    $env->setUser($user);
    $env->setInsertionTime(new DateTime());

    $env->save();
}

function findUser($id) {
    $user = UserQuery::create()->filterByUserId($id)->findOneOrCreate();
    return $user;
}

I can insert more than one environment on the same page but I don't want to recreate the user if it already exists.

Right now, it creates one user each time I insert an environment (during the same page execution, afterwards it works as expected).

How can I force the insertion of the user so that the next time I want to access it it already exists?

Is there another way to achieve this without forcing a "flush" ? I don't want to keep track of the users by hand.

Edit: I changed the way I create the user (code above edited), but it does not help.

I found a workaround, which is to disable the pooling.

Propel::disableInstancePooling();

To add in the setup.php file. But it then disable the feature completely, which drains performances down.

What about adding a new method in your ActiveRecord model ?

Something like that for instance:

<?php

class User extends BaseUser
{
    // Override the generated method
    public function addEnvironment($env)
    {
        $env->setInsertionTime(new DateTime());

        parent::addEnvironment($env);
    }
}

Then, start by finding or creating your user:

<?php

$user = UserQuery::create()->filterByUserId($id)->findOneOrCreate();

for ($i = 0; $i < $nbEnvironments; $i++) {
    $user->addEnvironment(new Environment());
}

// Save all
$user->save();

You won't get more than one user object, and you'll be able to use only one transaction for all your data manipulations. As you want to insert some environments to a user, it seems better to add this logic to the User ActiveRecord model.