Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

propel

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();
}
like image 695
RayOnAir Avatar asked Sep 03 '12 16:09

RayOnAir


2 Answers

Another alternative, especially if you need to search several times is to get array of objects by id with $collection->getArrayCopy('Id').

$persons = PersonQuery::create()->find();
$personsById = $persons->getArrayCopy('Id');

Then you can do

$person = $personsById[3];

or

if (isset($personsById[3])) {
  $person = $personsById[3];
  ...
}
like image 167
Ventzy Kunev Avatar answered Oct 18 '22 21:10

Ventzy Kunev


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());
like image 34
j0k Avatar answered Oct 18 '22 21:10

j0k