gpt4 book ai didi

symfony - dql 查询错误类未定义

转载 作者:行者123 更新时间:2023-12-04 03:57:25 25 4
gpt4 key购买 nike

试图将我的 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;
}
}

最佳答案

通过 namespace 引用 DQL 中的实体,即 AppBundle:ArticleAppBundle:User ,这应该会使错误消失。

使用 association mapping ( old docs ) 而不是 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();

关于symfony - dql 查询错误类未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32570983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com