【发布时间】:2015-03-16 16:40:40
【问题描述】:
我有两张桌子: 存档
+-------------+--------------+------+-----+---------+----------------+
| 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 | |
+------------+---------+------+-----+---------+-------+
这些表是通过多对多关系链接的,当然我也有一个用户表。运行 php app/console 学说:schema:update 生成集合表,并有实体定义:
用户实体
/**
* @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;
存档实体
/**
* @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 |
+----+---------------+--------------+---------+
如何使用学说 DQB/DQL 翻译上述查询?非常感谢
【问题讨论】:
-
如果不清楚就问
-
使用属性
present在您的 2 个实体之间添加一个实体 ArchiveContact,并在此新实体上进行查询。 -
嗨,Veve,你能举个例子吗?我用实体定义更新了我的问题。谢谢
-
看看我下面的答案,它包含一个例子;)
-
我无法根据我的需要调整这个示例。我将使用学说的 createNativeQuery。无论如何感谢您的帮助。
标签: php sql symfony doctrine-orm