R
R
Rukis2019-01-07 02:28:07
Doctrine ORM
Rukis, 2019-01-07 02:28:07

Is there an equivalent of Eloquetn scopes for Doctrine ORM?

Eloquetn ORM has a wonderful scopes functionality https://laravel.com/docs/5.7/eloquent#query-scopes
In short, these are query blanks that allow you to name a certain expression and then use it to expand other queries. Moreover, they can be dynamic - they take some parameters as input, for substitution in the request or changing the logic of its formation.
For example, we have several different requests to get a list of posts, but in each of these requests it is necessary to limit the selection according to a number of criteria that are the same for all requests. Let's say we decide whether or not to display a post based on several parameters: the role of the user, whether he is the author, what status the post is in, when it was published.
With eloquetn, we simply create a method like scopeVisable() on the Post model:

public function scopeVisable($query, User $user)
{
     ...
     return $query->where(...);
}

and then, when forming any request for receiving posts, we can use this blank when building a request: $posts = Post::visable($user)->get();
How is it customary to solve such problems with doctrine?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2019-01-07
@sidni

Well, in principle, it is possible to implement this only, that the Repository pattern is adopted in the Doctrine, and all query construction occurs within the framework of this repository, well, if you can primitively do this

//class BlogPostRepository
 
    private function active(QueryBuilder $qb)
    {
        return $qb->andWhere($this->alias.'.status = :activeStatus')
                    ->setParameter('activeStatus', BlogPost::STATUS_ACTIVE);
    }

public function findByUser(User $user)
    {
        $qb =  $this->createQueryBuilder($this->alias);
        $this->active($qb);
        return $qb->andWhere($this->alias.'.user = :user')
               ->setParameter('user', $user)
               ->getQuery()
               ->getResult();
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question