0

I have a User entity which has an ArrayCollection of Positions. Each Position has for sure a user_id property.

Now i want to get all positions from a user (to get all i would do $user->getPositions()) that are matching a specific query, for example have a date property that matches the current date. Therefor i want to do something like $user->getCurrentPositions() and it should return a subset of the positions related to that user.

How is that possible?

EDIT:

What i really wanna do is something like this in my controller:

$em = $this->getDoctrine()->getManager();
$users = $em->getRepository('fabianbartschWhereMyNomadsAtBundle:User')->findAll();

foreach ($users as $user) {
  $positions =  $user->getCurrentPositions();

  foreach ($positions as $position) {
    echo $position->getLatitude().'<br>';
  }
}

I wanna iterate over all users and from each user i want to have the relevant positions. But that isnt possible from the repository i guess, as i get the following message: Attempted to call method "getCurrentPositions" on class ...

1
  • You would create the method with the query in your repository class??? Commented Aug 17, 2014 at 18:46

2 Answers 2

1

If you are using Doctrine you can use the built-in Criteria API which is meant for this purpose exactly.

Collections have a filtering API that allows you to slice parts of data from a collection. If the collection has not been loaded from the database yet, the filtering API can work on the SQL level to make optimized access to large collections.

Sign up to request clarification or add additional context in comments.

Comments

0

Ok i found out, its for sure possible with Repositories:

Entity\User.php

/**
 * @ORM\Entity(repositoryClass="fabianbartsch\WhereMyNomadsAtBundle\Entity\UserRepository")
 * @ORM\Table(name="fos_user")
 */
 class User extends BaseUser
 {

Entity\UserRepository.php

/**
 * UserRepository
 */
class UserRepository extends EntityRepository
{
    public function getCurrentPositions()
    {
        $query = $this->getEntityManager()
            ->createQuery(
                "SELECT p
                 FROM xxx:Position p
                 WHERE p.start <= '2014-08-17' AND p.end >= '2014-08-17'"
            );

        try {
            return $query->getResult();
        } catch (\Doctrine\ORM\NoResultException $e) {
            return null;
        }
    }
}

In the user object only related position entries are affected by the query, so is no need to join user entity with the position entity. Pretty simple, should just try out instead posting on stackoverflow, sry guys :P

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.