symfony2 doctrine:学说中的多对多关系和SUBQUERY

时间:2015-03-16 16:40:40

标签: php sql symfony doctrine-orm

我有两张桌子: 存档

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| author      | varchar(100) | NO   |     | NULL    |                |
| title       | varchar(100) | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

和集合

+------------+---------+------+-----+---------+-------+
| Field      | Type    | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| user_id    | int(11) | NO   | PRI | NULL    |       |
| archive_id | int(11) | NO   | PRI | NULL    |       |
+------------+---------+------+-----+---------+-------+

这些表与ManyToMany关系链接,当然我也有一个用户表。生成集合表运行php app / console doctrine:schema:update并且有实体定义:

USER ENTITY

/**
* @ORM\OneToMany(targetEntity="My\ApplicationBundle\Entity\Archive", mappedBy="user")
**/
protected $archives;

/**
* @ORM\ManyToMany(targetEntity="My\ApplicationBundle\Entity\Archive", inversedBy="users")
* @ORM\JoinTable(name="collection")
**/
private $collection;

ARCHIVE ENTITY

/**
* @ORM\ManyToOne(targetEntity="My\UserBundle\Entity\User", inversedBy="archives")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
**/
protected $user;

/**
* @ORM\ManyToMany(targetEntity="My\UserBundle\Entity\User", mappedBy="collection")
**/
private $users;

当我在存档表中搜索某些内容时,es:

select a.id, a.author, a.title, IF((select c.archive_id from collection c where c.archive_id = a.id and c.user_id = 1),1,0) as present from archive a;

我还会有一个列,指示用户(es:id:1)是否在其集合中包含此存档,因此我的结果集应该类似于

+----+---------------+--------------+---------+
| id | author        | title        | present |
+----+---------------+--------------+---------+
|  8 | test author 7 | test title 7 |       1 |
|  9 | test author 8 | title 8      |       0 |
| 10 | test 8 pdf    | title 9 pdf  |       1 |
+----+---------------+--------------+---------+

如何使用doctrine DQB / DQL翻译上面的查询?非常感谢

1 个答案:

答案 0 :(得分:0)

在具有属性ArchiveContact的2个实体之间添加实体present,并查询此新实体。

此类实体from Doctrine documentation的示例,实体order代替user,实体product代替archive,属性{{1而不是offeredPrice

  

在经典订单产品商店的例子中,有一个概念   订单商品,其中包含对订单和产品的引用   其他数据,如购买的产品数量和可能   即使是现在的价格。

present