问题
I have two entites
Order
oneToMany:
statuses:
targetEntity: \Status
mappedBy: order
Status
manyToOne:
order:
targetEntity: \Order
inversedBy: status
fields:
code:
type:integer
As you can see - one order can have more that one status at a time (statuses like 'has been shipped', 'has been paid for etc.').
I want to write a query that fetch all my Orders that do NOT have a status of 6. I'm finding it hard to get my head round this.
Assume that I have three orders. The all have a status of '1' (new), and ONE of those orders additionally has a status of '6' (under review). I want to retrieve only the two orders that do NOT have a status of 6.
Writing the query like so..
$qb->select('o')
->from('MyOrderBundle:Order', 'o')
->innerJoin('o.statuses', 'st')
->where(
$qb->expr()->not(
$qb->expr()->eq('st.code', 6)
)
);
Excludes the status row of 6 from the SQL generated, but still includes the order in the result set (because the status row where the code=1 matches the condition of not being equal to 6). I need to be able to say "Exclude from my result set any entity that has an association like {something}". Is there a DQL keyword that can help me here?
-Cross posting on the doctrine user group and will update answers In both place if I find a solution.
回答1:
I worked out a way to do this eventually using a subselect, which feels a bit hacky but I couldn't think of any other way (where 6,7,8,9 are statuses that I want to exclude from my result set).
$qb->select('o')
->from('MyOrderBundle:Order', 'o')
->innerJoin('o.statuses', 'st')
->where(
$qb->expr()->notIn(
$qb2->select('DISTINCT(o2.id)')
->from('MyOrderBundle:Status', 'stat')
->innerJoin('stat.order','o2','WITH', $qb2->expr()->in('stat.code', (6,7,8,9)))->getDQL()
)
);
来源:https://stackoverflow.com/questions/10638926/doctrine-dql-querybuilder-excluding-entities-where-relationship-exists