未定义dql查询错误类

时间:2015-09-14 17:58:38

标签: symfony doctrine dql

尝试将我的sql查询转换为dql,似乎我做错了。

我需要基本的连接,就像这样。

SELECT a.id, a.title, u.name FROM articles JOIN users ON a.author_id = u.id

尝试

SELECT a.id, a.title, u.name FROM Article a JOIN User u WITH a.author_id = u.id

获取错误

[Semantical Error] line 0, col 34 near 'Article a JOIN': Error: Class 'Article' is not defined.

我该如何定义?你能给我一个正确的解决方案吗?

编辑:

文章实体

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="articles")
 */
class Article
{
    /**
     * @var integer $id
     *
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $title;


    /**
     * @ORM\Column(type="integer", name="author_id")
     */
    protected $authorId;

    /**
     * @ORM\Column(type="datetime", name="creation_date")
     */
    protected $creationDate;

    /**
     * @ORM\Column(type="string", name="short_content")
     */
    protected $shortContent;

    /**
     * @ORM\Column(type="string")
     */
    protected $content;

    public function getId()
    {
        return $this->id;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function getAuthorId()
    {
        return $this->authorId;
    }

    public function getCreationDate()
    {
        return $this->creationDate;
    }

    public function getShortContent()
    {
        return $this->shortContent;
    }

    public function getContent()
    {
        return $this->content;
    }
}

用户实体

<?php
namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="bigint")
     */
    protected $phone;

    /**
     * @ORM\Column(type="string")
     */
    protected $gender;

    /**
     * @ORM\Column(type="string")
     */
    protected $about;

    public function getPhone()
    {
        return $this->phone;
    }

    public function getGender()
    {
        return $this->gender;
    }

    public function getAbout()
    {
        return $this->about;
    }
}

1 个答案:

答案 0 :(得分:9)

请参阅DQL中按其名称空间划分的实体,即AppBundle:ArticleAppBundle:User,这样可能会导致错误消失。

我强烈建议您在实体中使用association mapping而不是authorId,这样Doctrine将处理“自动”加载作者:

/** 
 * @ORM\ManyToOne(targetEntity="User") 
 * @ORM\JoinColumn(name="author_id", referencedColumnName="id") 
 **/ 
private $author;

public function getAuthor() {
    return $this->author;
}

public function setAuthor($author) {
   $this->author = $author;
}

您的查询将缩减为:

SELECT a FROM AppBundle:Article a ORDER BY a.creationDate DESC

加载文章后,您可以方便地访问作者:

...
$author = $article->getAuthor();