我的博客
在这里,我在 Twig 中检索用户的代码遇到了一些问题,我在 Article 表和 User 表之间有一个 ManyToOne 关系,我想检索文章的作者,但我不能。在数据库中一切都很好,但在Twig中我不知道该怎么做。
周一代码
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 App\Entity;
use App\Repository\ArticleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=ArticleRepository::class)
*/
class Article
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=50)
*/
private $titre;
/**
* @ORM\Column(type="string", length=255)
*/
private $description;
/**
* @ORM\Column(type="text")
*/
private $contenu;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $photo;
/**
* @ORM\Column(type="string", length=255)
*/
private $slug;
/**
* @ORM\Column(type="datetime")
*/
private $created_at;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $updated_at;
/**
* @ORM\OneToMany(targetEntity=Commentaire::class, mappedBy="articles", orphanRemoval=true)
*/
private $commentaires;
/**
* @ORM\ManyToMany(targetEntity=Categorie::class, inversedBy="articles")
*/
private $categories;
/**
* @ORM\ManyToOne(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;
}
}
用户.php
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @UniqueEntity(fields={"email"}, message="There is already an account with this email")
*/
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORM\Column(type="string")
*/
private $password;
/**
* @ORM\Column(type="boolean")
*/
private $isVerified = false;
/**
* @ORM\Column(type="string", length=50)
*/
private $nom;
/**
* @ORM\Column(type="string", length=50)
*/
private $prenom;
/**
* @ORM\OneToMany(targetEntity=Article::class, mappedBy="users")
*/
private $articles;
/**
* @ORM\OneToMany(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)。
这意味着错误可能出现在用户属性上方的注释中。通过查看您的代码,引起我注意的一件事是您指向 targetEntity 时的语法。您正在使用 User::class,但根据学说文档,它应该像这样 targetEntity="User" 或像这样 targetEntity="App\Entity\User"
/**
* @ORM\ManyToOne(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();
}
代码很完美,我遇到的唯一问题是在连接之前创建了一些文章,因此用户在数据库中为空并且无法显示它。 我删除了这些文章,问题已经解决了。