简体   繁体   中英

Doctrine: how to get two entities' objects from two tables with different clauses?

There are two entity classes, I want to fetch their objects from MySQL table within one query:

SELECT d, e 
        FROM OrganizerBundle:DailyTask d, OrganizerBundle:Event e
        WHERE d.weekday = 'all' OR DATE_FORMAT(e.date,'%Y-%m-%d') = :date

As you see, I need DailyTasks with weekday = 'all' and Events with date = :date. The problem is - WHERE works only for first table (weekday = 'all') + I get all objects from second table. How to separate WHERE clauses for two entities?

As stated above, within Doctrine 2 what you want is not possible.

You state that you want to build one table from this data. I would suggest using native SQL, and use MySQL's powerful INSERT INTO ... SELECT ... .

I have no idea what your table structure is, both of your new table and your old tables, so I'm just guessing that a UNION could help you put this in a single query, but otherwise simply use two different inserts.

Note that UNION is mostly neat when two tables have a similar structure. I'm guessing from your entity names that Events and DailyTasks both have a date and some other common fields.

You'd get something like this:

$em = $this->getDoctrine()->getManager(); $sql = "INSERT INTO newtable (date, description) SELECT date, description FROM (SELECT date, description FROM dailytask WHERE weekday = 'all') UNION (SELECT date, description FROM event WHERE DATE_FORMAT(e.date,'%Y-%m-%d') = ?)"; $stmt = $em->getConnection()->prepare($sql); $stmt->execute();

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