H
H
HellWalk2021-06-24 15:56:35
Doctrine ORM
HellWalk, 2021-06-24 15:56:35

How to join unrelated entities in QueryBuilder?

An elementary request, with which, for some reason, difficulties arose.

So, there are two entities (tables) that are not related to each other (there is no foreign key):

60d48029d59a4367849774.png

60d480320e1e4816639653.png

You need to build a query like this through createQueryBuilder:

SELECT post.title, view.views FROM post
JOIN view ON post.title = view.post
WHERE view.views > 0;


Writing:
public function getPosts(): array
    {
        return $this->createQueryBuilder('p')
            ->join(View::class, 'v', 'ON', 'p.title = v.post')
            ->where('v.views > 0')
            ->getQuery()
            ->getResult()
            ;
    }


I am getting an error:

QueryException: [Syntax Error] line 0, col 61: Error: Expected end of string, got 'ON'


If the entities are interconnected through a property, then there are no problems to join. But is it really necessary to first bind entities through a property in order to then make the necessary join in the QueryBuilder?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BoShurik, 2021-06-24
@HellWalk

return $this->createQueryBuilder('p')
    ->join(View::class, 'v', 'WITH', 'p.title = v.post')
    ->where('v.views > 0')
    ->getQuery()
    ->getResult()
;

S
sl0, 2021-06-24
@sl0

It is possible to try to make through raw sql.
But in general, logically, these entities should be connected. Firstly, infa is duplicated in vain, and secondly, violating the consistency of the database is as easy as shelling pears.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question