Lex Hartman
Lex Hartman

Reputation: 178

Get element from ArrayCollection

I want to get 1 element out an ArrayCollection. I'm using Symfony 2.7.

For example i have an collection of the entity Activity:

$activities = $em->getRepository('AppBundle:Activity')->findAll();

Next i want to get 1 activity out of this ArrayCollection, based on a many-to-one relation.

The entity 'Activity':

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ActivityRepository")
 * @ORM\Table(name="activity")
 */
class Activity {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="ObjectElementTask", inversedBy="activities", cascade={"persist"})
     * @ORM\JoinColumn(name="objectelementtask_id", referencedColumnName="id", onDelete="CASCADE")
     */
    private $objectelementtask;

What did i try:

$objectElementTask = $em->getRepository('AppBundle:ObjectElementTask')->findOneBy(["active" => 1, "object" => (int)$objectId]);    
$activity = $activities->findBy(['objectelementtask' => $objectElementTask]);

I get the following exception: "Call to a member function findBy() on array"

I want to prevent querying the database foreach.

I also tried:

$activity = array_search($objectElementTask, array_column($activities, 'objectelementtask'));

But this has no result...

Thanks in advance!

Upvotes: 0

Views: 6234

Answers (1)

Ollie in PGH
Ollie in PGH

Reputation: 2629

There are a couple things that I can see here.

1) Doctrine queries return an array not an ArrayCollection. (https://stackoverflow.com/a/8237943/7745506). That's why you're getting the error on findBy. (I don't even think ArrayCollection has a findBy method. Here's the API and I don't see it: http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html) If this were an ArrayCollection, you might be able to use the filter method: http://www.doctrine-project.org/api/common/2.3/source-class-Doctrine.Common.Collections.ArrayCollection.html#377-387

2) If your Activity class has a ManyToOne relationship with the ObjectElementTask class then by definition, any search for an Activity by ObjectElementTask has the potential to return many Activities.

3) You say you don't want to query the DB in a foreach and you don't need to.

What you can do in this situation is query the DB for all Activities (it has the potential to be multiple because of item 2 above) for a specific ObjectElementTask.

$objectElementTask = $em->getRepository('AppBundle:ObjectElementTask')->findOneBy(["active" => 1, "object" => (int)$objectId]);

$activities = $em->getRepository('AppBundle:Activity')->findBy(['objectelementtask' => $objectElementTask]);

This will return all Activities that have that ObjectElementTask as their objectelementtask. You'll have to figure out WHICH Activity you want after that because this will be an array.

Upvotes: 1

Related Questions