如何在不加入doctrine2的情况下获得id?

2022-01-03 00:00:00 php doctrine-orm

我有这样的实体:

/**
 *
 * @Table(name="table")
 * @Entity
 */
 class Table {

    /**
     * @Column(type="integer")
     * @Id
     * @GeneratedValue(strategy="IDENTITY")
     */
     private $id;


    /**
     * @ManyToOne(targetEntity="EntitiesUsers")
     * @joinColumn(name="userId", referencedColumnName="id")
     */
     private $User;


    /**
     * @Column(type="string")
     */
     private $text;


}

如果我这样做$q->getQuery()->getSingleResult()->getUser()->getUserId()

doctrine 生成查询,如:

doctrine generate query like:

SELECT * FROM table t INNER JOIN users u ON u.id = t.userId WHERE id = 100

但如果我不需要表用户,如何获取用户 ID.

but if i don`t need table users, how to get an userId.

在纯 SQL 中,我可以

In pure SQL i can just

SELECT * FROM table WHERE id = 100

并在不加入用户表的情况下获取 userId.

and get userId without join users table.

推荐答案

您可能还想查看 IDENTITY() 函数(Doctrine version >2.2).

You may also want to look at the IDENTITY() function (Doctrine version >2.2).

示例:

SELECT IDENTITY(t.User) AS user_id from Table

应该返回:

[ ['user_id' => 1], ['user_id' => 2], ... ]

另见:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#dql-functions

相关文章