Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 716
clifford.duke Avatar asked Dec 04 '25 17:12

clifford.duke


2 Answers

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'));
like image 79
RobMasters Avatar answered Dec 06 '25 08:12

RobMasters


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')
);
like image 32
Mohammed H Avatar answered Dec 06 '25 08:12

Mohammed H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!