Mike
Mike

Reputation: 12829

Doctrine - Get row or rows from many results based on column value

I am using doctrine with a one to many relationship where each user entity has many post entities. So I have a doctrine query like so

$em = $this->getDoctrine()->getManager();

$query = $em->createQuery(
   'SELECT u, p FROM MYUserBundle:User u
   JOIN u.post p'
);

I can then get the users posts like so

foreach($query->getResult() as $user){

   //a bunch of posts related to this user
   $posts = $user->getPosts();
}

For convenience I would like to create an API that will allow me to get a specific post or posts out of this $posts object based on a column value without using more queries. So for example I have a column named post_slug, so I would like to be able to say

$posts = $user->getPosts();
$post = $posts->findBySlug('my_slug');

//or something along those lines...

Is this something that can be done with the $posts object or Post entity class?

Upvotes: 0

Views: 3431

Answers (3)

Peter Bailey
Peter Bailey

Reputation: 105916

Doctrine's collections are filterable. So, assuming your Post entities are stored on User::$posts, do this in your user entity.

public function getPostsBySlug( $slug )
{
  return $this->posts->filter( function( Post $post ) use ( $slug )
  {
    return $post->getSlug() == $slug;
  } );
}

Then you can just do

$posts = $user->getPostsBySlug( 'my_slug' );

Upvotes: 5

Pappa
Pappa

Reputation: 1645

You can move this kind of functionality to a Repository class (extending EntityRepository).

For example:

namespace Acme\ThingBundle\Repository;

use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository
{
    public function getBySlug($slug)
    {
        /// your custom query here

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

Upvotes: 0

AdrienBrault
AdrienBrault

Reputation: 7745

What about doing

$slug = 'my_slug';
array_filter($user->getPosts()->all(), function ($post) use ($slug) {
    return $post->getSlug() == $slug;
})

Upvotes: 0

Related Questions