学说2:如何用sql代码列扩展实体?

时间:2012-11-04 12:54:16

标签: sql doctrine-orm native-sql customcolumn

我有实体

mh\BTBundle\Entity\Post:
    type: entity
    table: post
    repositoryClass: mh\BTBundle\Repository\PostRepository
    fields:
        id:
            id: true
            type: integer
            unsigned: true
            nullable: false
            generator:
                strategy: IDENTITY
        title:
            type: string
            length: 255
            nullable: false
        content:
            type: text
            nullable: false
        isModered:
            type: boolean
            nullable: false
        isPublished:
            type: boolean
            nullable: false
        pubDate:
            type: datetime
            nullable: false

现在只需1分钟的cron调用脚本,如果post有isModered = true和pubDate<设置为isPublished = true :现在。

$this->getEM()->createQueryBuilder()
            ->update('BTBundle:Post p')
            ->set('p.isPublished', 'true')
            ->where('p.pubDate < :date AND p.isModered = true')
            ->setParameter(':date', new \DateTime())
            ->getQuery()->execute();

但我想定义自定义列isPublished,如果SQL(p.pubDate < CURDATE() AND p.isModered = 1)则返回true。我该怎么做?

我想用

$posts = $this->getRepository('Post')->findBy(array(
            'user' => $user,
            'isPublished' => true,
        ));

而不是

$this->getEM()->createQueryBuilder()
                ->select('p')
                ->from('BTBundle:Post', 'p')
                ->where('p.isModered = true')
                ->andWhere('p.pubDate < :date')
                ->andWhere('p.user = :user')
                ->setParameter(':date', new \DateTime())
                ->setParameter(':user', $user)
                ->getQuery()->execute();

1 个答案:

答案 0 :(得分:0)

最简单的方法是创建一个计算column。就像这样。

CREATE TABLE dbo.Example
(
    ExampleId int IDENTITY (1,1) NOT NULL,
    Value1 INT
    Value2 INT
    ComputedCol AS Value1 + Value2
);

您可以在AS语句中使用任何有效的SQL逻辑。