【问题标题】:Doctrine OneByOne's and Date教义 OneByOne 和日期
【发布时间】:2015-06-19 13:11:39
【问题描述】:

我正在使用 Symfony 2.7.1,但在使用我的新闻实体时似乎遇到了问题。我正在尝试在我的树枝模板中使用 published_at。

我尝试使用{{ news_item.published_at|date("m/d/Y") }},但这似乎是一个致命错误:

Method "published_at" for object "AppBundle\Entity\News" does not exist in AppBundle:news:index.html.twig at line 7

第 7 行:

{{ news_item.published_at | date("m/d/Y") }}

我还在调试工具栏中收到“无效实体”警告,说明如下;

  • AppBundle\Entity\Account
    • 关联 AppBundle\Entity\Account#articles 指的是拥有方字段 AppBundle\Entity\News#author,它没有定义为关联,而是定义为字段。
    • 关联 AppBundle\Entity\Account#articles 是指不存在的拥有方字段 AppBundle\Entity\News#author。

这些是我的文件。我希望有人能帮助我把我推向正确的方向:

src/AppBundle/Entity/News.php

class News
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @ORM\Column(name="body", type="text")
     */
    private $body;

    /**
     * @ORM\Column(name="author", type="integer")
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Account", inversedBy="articles")
     */
    private $author;

    /**
     * @ORM\Column(name="published_at", type="datetime")
     */
    private $published_at;
}

src/AppBundle/Entity/Repositories/NewsRepository.php

class NewsRepository extends EntityRepository
{
    /**
     * @param $number
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findLatest($number) {
        return $this->createQueryBuilder('a')
            ->orderBy('a.published_at', 'DESC')
            ->setMaxResults($number)
            ->getQuery()
            ->getResult();
    }
}

src/AppBundle/Entity/Account.php

class Account implements AdvancedUserInterface
{
    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\News", mappedBy="author")
     */
    protected $articles;
}

【问题讨论】:

  • 由于您使用private 属性,您必须在您的实体中提供public get/set 方法,模板引擎将能够自动访问它们。是您添加了自己的,还是在此处复制代码时将它们忽略了?
  • @Artamiel:由于我的问题很长(以尽量减少垃圾),我将它们排除在外,但所有 get 和 setter 都是公开的。

标签: php symfony doctrine-orm entity


【解决方案1】:

您的实体类需要 getter(和 setter)。

class News
{
    // ...

    /**
     * @ORM\Column(name="published_at", type="datetime")
     */
    private $published_at;

    public function getPublished_at()
    {
        return $this->published_at;
    }
}

用这个{{ news_item.published_at }}will callNews::getPublished_at

(...) 如果不是,并且如果 foo 是一个对象,检查 getBar 是一个有效的方法; (...)

你也可以直接在twig中用{{ news_item.getPublished_at() }}获取方法

【讨论】:

  • 我确实有 get 和 setter。由于我的问题很长(以尽量减少垃圾),我把他们排除在这个问题之外。但是,您建议的实体并没有解决我的问题。我使用了published_at 而不是publishat。它确实解决了我的问题。谢谢。
猜你喜欢
  • 2013-06-03
  • 1970-01-01
  • 2011-10-05
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
  • 2012-06-05
  • 2016-06-15
相关资源
最近更新 更多