What is the syntax for a multi-table delete on a MySQL database using Doctrine?

半城伤御伤魂 提交于 2019-12-24 01:27:12

问题


Using Doctrine, I am trying to delete records in a single table based on data gathered from multiple tables.

'companies_groups' is an association table linking 'companies' to 'groups'. I want to delete all records in this table linked to a specific company, with the restriction that only 'companies_groups' records linked to a 'public' group will be deleted.

If I were to write this in pure SQL, it would look something like this:

DELETE companies_groups
FROM companies_groups, groups
WHERE companies_groups.companyID = 7
AND companies_groups.groupID = groups.id
AND groups.groupType = 'public'

What is the equivalent in Doctrine? I have been struggling and experimenting for an hour or so now.

At the moment I have this:

$query = Doctrine_Query::create()
  ->delete('Company_group cg')
  ->from('Company_group cg, Group g')
  ->where( "cg.companyID = ? AND g.groupType = 'public' AND g.id = cg.groupID ", array( $companyID ) );

(My Doctrine models are 'Company_group' for the 'companies_groups' table and 'Group' for the 'groups' table)

Which produces this SQL:

DELETE FROM companies_groups, groups WHERE (companyid = ? AND grouptype = 'public' AND id = groupid)

You can see that the generated SQL is missing 'companies_groups' between DELETE and FROM, and that the qualifiers are dropped (meaning 'id' will be ambiguous).

Let me know if there is any additional info I can provide that would be helpful.


回答1:


Solved it. Rather than try to build the join myself I used a subquery and didn't try to force Doctrine to construct the SQL in a specific way.

For anyone else that ever needs to do something like this, here is what ended up working:

$query = Doctrine_Query::create()
  ->delete('Company_group')
  ->where( "companyID = ?", array( $companyID ) )
  ->addWhere( "groupID IN (SELECT g.id FROM Group g WHERE g.groupType = 'public')" );

Cheers.



来源:https://stackoverflow.com/questions/2247905/what-is-the-syntax-for-a-multi-table-delete-on-a-mysql-database-using-doctrine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!