Search code examples
phppropel

How to get object by "id" from propel object collection?


I'm using Propel 1.6 and I'm not sure how to get an object (given its "id" attribute value) from a propel object collection. I could not find a straight answer in Propel's documentation (PropelCollection methods do not seem applicable?). For example: Lets say I have a "Person" table with the following schema:

<table name="person">
  <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" required="true"/>
  <column name="name" type="VARCHAR" size="100" required="true"/>
</table>

I do the following query to get a collection of "Person" objects:

$persons = PersonQuery::create()->find();

Then, I want to find a "Person" object with a given "id" (e.g. "Person" with "id=3"), without making a new query to the database. How can I do it?

$persons->get(...?)?

In other words, I DO NOT want to do:

$personX = PersonQuery::create()->findOneById(3);

Context:

I would like to prevent making a database query to improve performance. The statement is to be inserted inside a foreach statement that would otherwise lead to numerous database connections, like the following:

foreach ($books as $book) {
    $book['author_name'] = PersonQuery::create()->findOneById($book['author_id'])->getName();
}

Solution

  • Well, that won't be very efficient, but you can go through the collection to find it.

    $persons = PersonQuery::create()->find();
    foreach ($persons as $person)
    {
      if (3 == $person->getId())
      {
        break;
      }
    }
    
    // now you have your person with id = 3
    var_dump($person->getId());