我需要在树枝Symfony中检索用户



我的博客
这里我在Twig中检索用户的代码有点问题,我在Article表和user表之间有ManyToOne关系,我想检索文章的作者,但我不能。在数据库中一切都很好,但在Twig中我不知道该怎么做。
Mon代码

ArticleController.php

/**
* @Route("/add-article", name="add_article", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$article = new Article();
$form = $this->createForm(ArticleFormType::class, $article);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$article->setUsers($this->getUser());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($article);
$entityManager->flush();
return $this->redirectToRoute('blog_articles');
}
return $this->render('articles/Article-form.html.twig', [            
'form_title'=> 'Ajouter un Article',
'form_article' => $form->createView(),
]);
}  

我的推特

{% for  article in articles %}
<div class="col-md-6 col-lg-4">
<div class="card mb-4 shadow-sm">
<!-- CONDITIONS POUR L'AFFICHAGE DES PHOTOS-->
{% if article.photo is defined and article.photo is not null %}
<img src="{{asset('images/')}}{{ article.photo }}" class="img-fluid" width="100%" height="225">
{% else %}
<img src="{{asset('images/img-17.jpg')}}" class="img-fluid" width="100%" height="225">
{% endif %}
<div class="card-body">
<!--BOUCLE POUR RECUPERER LE CATEGORIE DE CHAQUE ARTICLE-->
{% for categorie in article.categories %}
<span class="text-left" style="color: grey;">{{ categorie.nom }}</span>
{% endfor %}
<!-- FIN DE LA BOUCLE-->
<h4 class="text-center titre">
<a href="{{ path('blog_article', {'id': article.id}) }}"> {{ article.titre }} </a>
</h4>
<p class="card-text">{{ article.description }}</p>
<div class="d-flex justify-content-between align-items-center">
<!-- Post Author -->
<p class="text-muted">{{ article.users.nom }} - {{ article.createdAt| date('d/m/Y')}}</p>
<div class="social">
<ul class="list-inline">
<a href="" class="mr-4"><i class="fa fa-heart" aria-hidden="true"></i> 3 </a>
<a href=""><i class="fas fa-comments" aria-hidden="true"></i> 5 </a>
</ul>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
<!-- FIN DE LA BOUCLE POUR LES ARTICLES-->

我得到了什么

Impossible to access an attribute ("nom") on a null variable.

文章.php

<?php
namespace AppEntity;
use AppRepositoryArticleRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
/**
* @ORMEntity(repositoryClass=ArticleRepository::class)
*/
class Article
{
/**
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=50)
*/
private $titre;
/**
* @ORMColumn(type="string", length=255)
*/
private $description;
/**
* @ORMColumn(type="text")
*/
private $contenu;
/**
* @ORMColumn(type="string", length=255, nullable=true)
*/
private $photo;

/**
* @ORMColumn(type="string", length=255)
*/
private $slug;
/**
* @ORMColumn(type="datetime")
*/
private $created_at;
/**
* @ORMColumn(type="datetime", nullable=true)
*/
private $updated_at;
/**
* @ORMOneToMany(targetEntity=Commentaire::class, mappedBy="articles", orphanRemoval=true)
*/
private $commentaires;
/**
* @ORMManyToMany(targetEntity=Categorie::class, inversedBy="articles")
*/
private $categories;
/**
* @ORMManyToOne(targetEntity=User::class, inversedBy="articles")
*/
private $users;
public function __construct()
{
$this->commentaires = new ArrayCollection();
$this->categories = new ArrayCollection();
$this->created_at= new DateTime('now');
}
public function getId(): ?int
{
return $this->id;
}
public function getTitre(): ?string
{
return $this->titre;
}
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getContenu(): ?string
{
return $this->contenu;
}
public function setContenu(string $contenu): self
{
$this->contenu = $contenu;
return $this;
}
public function getPhoto(): ?string
{
return $this->photo;
}
public function setPhoto(?string $photo): self
{
$this->photo = $photo;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getCreatedAt(): ?DateTimeInterface
{
return $this->created_at;
}
public function setCreatedAt(DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
public function getUpdatedAt(): ?DateTimeInterface
{
return $this->updated_at;
}
public function setUpdatedAt(?DateTimeInterface $updated_at): self
{
$this->updated_at = $updated_at;
return $this;
}
/**
* @return Collection|Commentaire[]
*/
public function getCommentaires(): Collection
{
return $this->commentaires;
}
public function addCommentaire(Commentaire $commentaire): self
{
if (!$this->commentaires->contains($commentaire)) {
$this->commentaires[] = $commentaire;
$commentaire->setArticles($this);
}
return $this;
}
public function removeCommentaire(Commentaire $commentaire): self
{
if ($this->commentaires->removeElement($commentaire)) {
// set the owning side to null (unless already changed)
if ($commentaire->getArticles() === $this) {
$commentaire->setArticles(null);
}
}
return $this;
}
/**
* @return Collection|categorie[]
*/
public function getCategories(): Collection
{
return $this->categories;
}
public function addCategory(categorie $category): self
{
if (!$this->categories->contains($category)) {
$this->categories[] = $category;
}
return $this;
}
public function removeCategory(categorie $category): self
{
$this->categories->removeElement($category);
return $this;
}
public function getUsers(): ?user
{
return $this->users;
}
public function setUsers(?user $users): self
{
$this->users = $users;
return $this;
}
}

User.php

<?php
namespace AppEntity;
use AppRepositoryUserRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;
use SymfonyComponentSecurityCoreUserUserInterface;
/**
* @ORMEntity(repositoryClass=UserRepository::class)
* @UniqueEntity(fields={"email"}, message="There is already an account with this email")
*/
class User implements UserInterface
{
/**
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=180, unique=true)
*/
private $email;
/**
* @ORMColumn(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORMColumn(type="string")
*/
private $password;
/**
* @ORMColumn(type="boolean")
*/
private $isVerified = false;
/**
* @ORMColumn(type="string", length=50)
*/
private $nom;
/**
* @ORMColumn(type="string", length=50)
*/
private $prenom;
/**
* @ORMOneToMany(targetEntity=Article::class, mappedBy="users")
*/
private $articles;
/**
* @ORMOneToMany(targetEntity=Commentaire::class, mappedBy="users", orphanRemoval=true)
*/
private $commentaires;
public function __construct()
{
$this->articles = new ArrayCollection();
$this->commentaires = new ArrayCollection();
}
public function __toString()
{
return $this->prenom . ' ' . $this->nom; 
}

public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
/**
* @return Collection|Article[]
*/
public function getArticles(): Collection
{
return $this->articles;
}
public function addArticle(Article $article): self
{
if (!$this->articles->contains($article)) {
$this->articles[] = $article;
$article->setUsers($this);
}
return $this;
}
public function removeArticle(Article $article): self
{
if ($this->articles->removeElement($article)) {
// set the owning side to null (unless already changed)
if ($article->getUsers() === $this) {
$article->setUsers(null);
}
}
return $this;
}
/**
* @return Collection|Commentaire[]
*/
public function getCommentaires(): Collection
{
return $this->commentaires;
}
public function addCommentaire(Commentaire $commentaire): self
{
if (!$this->commentaires->contains($commentaire)) {
$this->commentaires[] = $commentaire;
$commentaire->setUsers($this);
}
return $this;
}
public function removeCommentaire(Commentaire $commentaire): self
{
if ($this->commentaires->removeElement($commentaire)) {
// set the owning side to null (unless already changed)
if ($commentaire->getUsers() === $this) {
$commentaire->setUsers(null);
}
}
return $this;
}
}

PhpMyAdmin
这是一篇文章,user_Id 1。很好,数据库里有我需要的所有信息。我的问题是我无法显示文章作者的姓名
很抱歉我的英语不太好。

错误消息表示文章的users属性为null,这导致我们在ORM映射中出错,因为您表示文章的数据库字段user_id具有正确的值(1(。

这意味着错误可能出现在users属性上方的注释中。通过查看您的代码,有一件事引起了我的注意,那就是指向targetEntity时的语法。您使用的是User::class,但根据条令文档,它应该是这样的targetEntity="用户";或者像这个targetEntity=";应用程序\实体\用户">

/**
* @ORMManyToOne(targetEntity=User::class, inversedBy="articles")
*/
private $users;

https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/association-mapping.html

我可能错了,学说可能接受所有这些语法,但我认为值得检查这一点

编辑-由于问题不是上面的问题,另一件需要检查的事情是填充Article对象的方法。我想你必须使用这样的getData((方法:

$form = $this->createForm(ArticleType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// new article object come back populated by the form
$article = $form->getData();
// record the new article
$em = $this->getDoctrine()->getManager();
$em->persist($article);
$em->flush();
}

代码非常完美,我遇到的唯一问题是一些文章是在连接之前创建的,因此用户在数据库中为null,无法显示它。我删除了这些文章,问题已经解决了。

最新更新