简体   繁体   中英

How can I make a field in a Symfony2 form, using querybuilder, excluding entities without a many-to-many relation?

In my Symfony2 app, people can write texts that will be published on a webpage. There is an option to write a new text, and you have to select the webpage it will belong to.

What I want to achieve, is that this list of webpages shows webpages that do not yet have a text only. Otherwise you will end up replacing an existing text.

So I would like to write something like this in my form type :

$qb->select('wp')
->from('MyBundle:Webpage', 'wp')
->where('wp.webtexts is null')
->orderBy('wp.id');

The problem arises around the "wp.webtexts is null" statement. This is a (fully functioning) many-to-many relationship, and I would like to test whether there are no relations here. The error I receive, is:

[Semantical Error] line 0, col 70 near 'webtexts is null': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.

How can I query for webpages, with no relations to any webtexts?

Added:

How could I count the amount of relations? This notation:

 $qb->where($qb->expr()->count('wp.webtexts < 1'))

...gives me:

[Syntax Error] line 0, col 85: Error: Expected Doctrine\\ORM\\Query\\Lexer::T_CLOSE_PARENTHESIS, got '<'

If you are trying to check against the webtexts object you should query the webtexts id field rather than the webtexts object. Doctrine is still trying to write SQL at the end of the day and in SQL you would have to query a field:

$qb->select('wp')
    ->from('MyBundle:Webpage', 'wp')
    ->leftJoin('wp.webtexts', 'wt')
    ->where('wt.id IS NULL')
    ->orderBy('wp.id');

Like this:

$em->createQuery('SELECT wp FROM MyBundle:Webpage wp LEFT JOIN wp.webtexts wt WHERE wt.id IS NULL ORDER BY wp.id');

It takes Webpages that are joined or not with texts and then eliminates thoses which have a relation with text... So you've got webpages without relation !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM