Trying to conver my sql queries into dql, seems im doing something wrong.
I need basic joins, something like this.
SELECT a.id, a.title, u.name FROM articles JOIN users ON a.author_id = u.id
Tried
SELECT a.id, a.title, u.name FROM Article a JOIN User u WITH a.author_id = u.id
Getting error
[Semantical Error] line 0, col 34 near 'Article a JOIN': Error: Class 'Article' is not defined.
How should i define? Could you give me please a right solution?
Edit:
Article Entity
<?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;
}
}
User Entity
<?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;
}
}
Refer to the entities in your DQL by their namespaces, i.e. AppBundle:Article
and AppBundle:User
, that should make the error go away.
Use association mapping (old docs) instead of authorId
in your entity, this way Doctrine will take care of loading the author:
/**
* @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;
}
Your query would be reduced to:
SELECT a FROM AppBundle:Article a ORDER BY a.creationDate DESC
Once you have loaded an article, you can conveniently access the author:
...
$author = $article->getAuthor();