clifford.duke
clifford.duke

Reputation: 4040

Symfony - Get Entity Repository with multiple ID's

I have an entity that has multiple keys, how would I go about finding the proper object based on multiple ids?

$product = $em->getRepository('AcmeStoreBundle:Product')->find($id);

Upvotes: 3

Views: 12139

Answers (2)

RobMasters
RobMasters

Reputation: 4148

It's a little confusing what you're asking here. It sounds as though you have an entity with a compound key (primary key relates to multiple columns) and want to find it based on it's primary key values, yes?

If so, the find method will require an array containing values for each of the fields that make up the key:

$product = $em->getRepository('AcmeStoreBundle:Product')->find(array(
    'key1' => 'value1', 
    'key2' => 'value2'
));

Alternatively, you could use findOneBy method. This would be useful for when the combination of the provided fields are not unique as you're able to provide a second argument to define the ordering.

$product = $em->getRepository('AcmeStoreBundle:Product')->findOneBy(array(
    'key1' => 'value1', 
    'key2' => 'value2'
), array('updated_at' => 'DESC'));

Upvotes: 7

Mohammed H
Mohammed H

Reputation: 7048

See http://symfony.com/doc/2.0/book/doctrine.html#fetching-objects-from-the-database

$product = $em->getRepository('AcmeStoreBundle:Product')->findBy(
    array('key1' => 'value1', 'key2'=>'value2')
);

Upvotes: 1

Related Questions