我在Symfony项目的class table inheritance设置中使用自动生成的getter。 getId()
返回null,而其他每个getter都有效。你能发现任何问题吗?我应该搜索什么?我手动导入了数据库条目,但我不认为这是原因。
//src/Acme/WebzineBundle/Entity/Content.php
namespace Acme\WebzineBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Content
*
* @ORM\Table()
* @ORM\Entity
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="heading", type="integer")
* @ORM\DiscriminatorMap({
* 0 = "Review"
* })
*/
abstract class Content
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var \DateTime
*
* @ORM\Column(name="edited", type="date")
*/
private $edited;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get edited
*
* @return \DateTime
*/
public function getEdited()
{
return $this->edited;
}
}
//src/Acme/WebzineBundle/Entity/Review.php
namespace Acme\WebzineBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Review articles
*
* @ORM\Table()
* @ORM\Entity
*/
class Review extends Content
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=127)
*/
private $title;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
}
下一个外键约束在子实体的表上:
CONSTRAINT `FK_7EEF84F0BF396750` FOREIGN KEY (`id`) REFERENCES `Content` (`id`)
ON DELETE CASCADE
//src/Acme/AdminBundle/Controller/MainController.php
namespace Acme\AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class MainController extends Controller
{
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT post FROM AcmeWebzineBundle:Content post
ORDER BY post.edited DESC'
);
$query->setMaxResults(30);
$posts = $query->getResult();
$latest_post = $posts[0];
return $this->render('AcmeAdminBundle:Main:index.html.twig', array(
'posts' => $posts,
'id' => gettype($latest_post->getId()), // This returns null!
'edited' => $latest_post->getEdited(), // Any other getter works
'title' => $latest_post->getTitle(), // also from the child entity.
));
}
}
答案 0 :(得分:5)
您需要从子类
中删除id
属性和getId()
方法
//src/Acme/WebzineBundle/Entity/Review.php
namespace Acme\WebzineBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Review articles
*
* @ORM\Table()
* @ORM\Entity
*/
class Review extends Content
{
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=127)
*/
private $title;
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
}
您无法创建Content
类的对象。
更好仅使用Review
类中的唯一属性和方法,因为其他属性和方法都是从抽象Content
类继承的。