Need to create a query for two joined Doctrine entities

I have 2 entities, Models and User, with manytomany relations for $models and $users. I need to create a query that produce all $models for a specific $users that matches a specific $title string.

 /**
 * @ORMManyToMany(targetEntity="ThreeWebOneEntityBundleEntityUser", 
   inversedBy="models")
 * @ORMJoinTable(name="user_models")
 */
 protected $users;

/**
 * @ORMManyToMany(targetEntity="ThreeWebOneEntityBundleEntityModel", 
   mappedBy="users")
 * @ORMJoinTable(name="user_models")
 */
 protected $models;

I was able to get this query to work but it only produces an array of the titles field.

/**
 * Returns distinct array of users models titles
 *
 * @param User $user
 *
 * @return array
 */
public function getModelTitlesForUser(User $user)
{
    $qb = $this->createQueryBuilder('m')
        ->select('distinct(m.title) as title')
        ->innerJoin('m.users', 'u')
        ->where('u.id = :user_id')
        ->setParameter('user_id', $user->getId());
    $this->useResultCacheOnQuery($qb);

    return $qb->getQuery()->getResult();
}

But I need an array of Models objects instead.

Below is my best attempt but it doesn’t get any results:

 /**
 * Return distinct array of users models 
 *
 * @param int $userId
 *
 * @param $title
 * @return array
 */
 public function getModelsForUser($userId, $title)
 {
    $qb = $this->createQueryBuilder('m')
        ->innerJoin('m.users', 'u')
        ->where('u.user_id = :user_id')
        ->andWhere('m.title = :title')
        ->setParameter('user_id', $userId)
        ->setParameter('title', $title);

    $this->useResultCacheOnQuery($qb);

    return $qb->getQuery()->getResult();
 }

What am I doing wrong?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *