Bonjour ou bonsoir selon le moment!
Je développe une plateforme qui permettra de mettre en relation les agents immobiliers qui ont des biens à vendre ou à loués et les clients...
Je fais face à un problème qui m’empêche d'avancer. Je vais très vite décrire mon problème:
J'ai trois entites: User, Property et Message
User - Property : relation ManyToOne c'est à dire un User peut avoir plusieurs Properties et une Property est pour un User
Property - Message : relation ManyToOne c'est à dire une Property peut avoir plusieurs Messages et un Message est pour une ou zero Property
Précision: symfony 6
Je sais récupérer les Messages par Property : c'est à dire tous les Messages pour une Property
Maintenant Je veux récupérer tous les Messages qui sont pour un user et je ne sais pas comment m'y prendre. merci de votre aide
Entity User
"<?php
namespace App\Entity;
use Cocur\Slugify\Slugify;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: 'users')]
#[ORM\HasLifecycleCallbacks]
#[UniqueEntity(fields: ['email'], message: 'There is already an account with this email')]
// #[Vich\Uploadable]
/**
* @Vich\Uploadable
*/
class User implements UserInterface, \Serializable, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string', length: 180, unique: true)]
#[Assert\NotBlank]
#[Assert\Email(message: 'Is not a valid email.')]
private $email;
#[ORM\Column(type: 'json')]
private $roles = [];
#[ORM\Column(type: 'string')]
private $password;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Length(min: 3)]
private $firstName;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Length(min: 3)]
private $lastName;
#[ORM\Column(type: 'text')]
#[Assert\NotBlank]
#[Assert\Length(min: 16)]
private $description;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Regex('/[0-9]/')]
#[Assert\Length(min: 5, max: 20)]
private $phone;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
#[Assert\Regex('/[0-9]/')]
#[Assert\Length(min: 5, max: 20)]
private $mobile;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* @Vich\UploadableField(mapping="user_image", fileNameProperty="imageName")
* @Assert\Image(maxSize="8M")
*
* @var File|null
*/
private $imageFile;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private $imageName;
#[ORM\Column(
type: 'datetime',
options: ["default" => "CURRENT_TIMESTAMP"]
)]
private $createdAt;
#[ORM\Column(
type: 'datetime',
options: ["default" => "CURRENT_TIMESTAMP"]
)]
private $updatedAt;
#[ORM\OneToMany(mappedBy: 'user', targetEntity: Property::class, orphanRemoval: true)]
private $properties;
#[ORM\OneToMany(mappedBy: 'user', targetEntity: Blogpost::class, orphanRemoval: true)]
private $blogposts;
#[ORM\Column(type: 'boolean')]
private $isVerified = false;
public function __construct()
{
$this->properties = new ArrayCollection();
$this->blogposts = new ArrayCollection();
}
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 getUserIdentifier(): 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 PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(?string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(?string $lastName): self
{
$this->lastName = $lastName;
return $this;
}
public function getFullName(): string
{
return $this->getFirstName() . ' ' . $this->getLastName();
}
public function getSlug(): string
{
return (new Slugify())->slugify($this->getFullName());
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(?string $phone): self
{
$this->phone = $phone;
return $this;
}
public function getMobile(): ?string
{
return $this->mobile;
}
public function setMobile(?string $mobile): self
{
$this->mobile = $mobile;
return $this;
}
/**
* @param File|\Symfony\Component\HttpFoundation\File\UploadedFile|null $imageFile
*/
public function setImageFile(?File $imageFile = null): void
{
$this->imageFile = $imageFile;
if (null !== $imageFile) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->setUpdatedAt(new \DateTimeImmutable);
}
}
public function getImageFile(): ?File
{
return $this->imageFile;
}
public function getImageName(): ?string
{
return $this->imageName;
}
public function setImageName(?string $imageName): self
{
$this->imageName = $imageName;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
#[ORM\PrePersist]
#[ORM\PreUpdate]
public function updateTimestamps()
{
if ($this->getCreatedAt() === null)
{
$this->setCreatedAt(new \DateTimeImmutable);
}
$this->setUpdatedAt(new \DateTimeImmutable);
}
public function serialize()
{
return serialize(array(
$this->id,
$this->email,
$this->password,
));
}
public function unserialize($serialized)
{
list(
$this->id,
$this->email,
$this->password,
) = unserialize($serialized);
}
/**
* @return Collection<int, Property>
*/
public function getProperties(): Collection
{
return $this->properties;
}
public function addProperty(Property $property): self
{
if (!$this->properties->contains($property)) {
$this->properties[] = $property;
$property->setUser($this);
}
return $this;
}
public function removeProperty(Property $property): self
{
if ($this->properties->removeElement($property)) {
// set the owning side to null (unless already changed)
if ($property->getUser() === $this) {
$property->setUser(null);
}
}
return $this;
}
/**
* @return Collection<int, Blogpost>
*/
public function getBlogposts(): Collection
{
return $this->blogposts;
}
public function addBlogpost(Blogpost $blogpost): self
{
if (!$this->blogposts->contains($blogpost)) {
$this->blogposts[] = $blogpost;
$blogpost->setUser($this);
}
return $this;
}
public function removeBlogpost(Blogpost $blogpost): self
{
if ($this->blogposts->removeElement($blogpost)) {
// set the owning side to null (unless already changed)
if ($blogpost->getUser() === $this) {
$blogpost->setUser(null);
}
}
return $this;
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
}
"
Entity Property
"<?php
namespace App\Entity;
use Cocur\Slugify\Slugify;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\PropertyRepository;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
#[ORM\Entity(repositoryClass: PropertyRepository::class)]
#[ORM\Table(name: 'properties')]
#[ORM\HasLifecycleCallbacks]
#[ORM\UniqueEntity('name')]
class Property
{
const HEAT = [
1 => 'No heating system',
2 => 'Electric',
3 => 'Fuel oil',
4 => 'Gas',
5 => 'Heat Pump',
6 => 'Solar',
7 => 'Water heaters',
8 => 'Wood'
];
const TYPE = [
1 => 'Appartement',
2 => 'Villa',
3 => 'Studio',
4 => 'Duplex'
];
const CATEGORY = [
1 => 'For Rent',
2 => 'For Sale'
];
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string', length: 255, unique: true)]
#[Assert\NotBlank(message: 'Give your property name')]
#[Assert\Length(min: 4)]
private $name;
#[ORM\Column(type: 'text')]
#[Assert\NotBlank]
#[Assert\Length(min: 16)]
private $description;
#[ORM\Column(type: 'integer')]
#[Assert\NotBlank]
#[Assert\Positive]
#[Assert\Range(min: 10, max: 1000)]
private $area;
#[ORM\Column(type: 'integer')]
#[Assert\NotBlank]
#[Assert\Positive]
#[Assert\Range(min: 1)]
private $rooms;
#[ORM\Column(type: 'integer')]
#[Assert\NotBlank]
#[Assert\Positive]
#[Assert\Range(min: 1)]
#[Assert\LessThanOrEqual(propertyPath: 'rooms')]
private $bedrooms;
#[ORM\Column(type: 'integer')]
#[Assert\NotBlank]
#[Assert\Positive]
#[Assert\Range(min: 1)]
#[Assert\LessThanOrEqual(propertyPath: 'rooms')]
private $bathrooms;
#[ORM\Column(type: 'integer')]
#[Assert\NotBlank]
#[Assert\Positive]
private $price;
#[ORM\Column(type: 'integer', nullable: true)]
#[Assert\PositiveOrZero]
private $floor;
#[ORM\Column(type: 'integer')]
#[Assert\NotBlank]
#[Assert\Positive(message: 'Please choose from the possible options')]
#[Assert\Range(max: 8)]
private $heat;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Length(min: 3)]
private $city;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Length(min: 3)]
private $address;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Country]
private $country;
#[ORM\Column(
type: 'boolean',
options: ["default" => false]
)]
private $sold = false;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Regex('/^[0-9]{5}$/')]
private $postalCode;
#[ORM\Column(type: 'integer')]
#[Assert\NotBlank]
#[Assert\Positive(message: 'Please choose from the possible options')]
#[Assert\Range(max: 4)]
private $type;
#[ORM\Column(type: 'integer')]
#[Assert\NotBlank]
#[Assert\Positive(message: 'Please choose from the possible options')]
#[Assert\Range(max: 2)]
private $category;
#[ORM\Column(type: 'integer')]
#[Assert\NotBlank]
#[Assert\PositiveOrZero]
private $garage;
#[ORM\Column(
type: 'datetime',
options: ["default" => "CURRENT_TIMESTAMP"]
)]
private $createdAt;
#[ORM\Column(
type: 'datetime',
options: ["default" => "CURRENT_TIMESTAMP"]
)]
private $updatedAt;
#[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'properties')]
#[ORM\JoinColumn(nullable: false)]
private $user;
#[ORM\ManyToMany(targetEntity: Option::class, inversedBy: 'properties')]
private $options;
#[ORM\OneToMany(mappedBy: 'property', targetEntity: Message::class, orphanRemoval: true)]
private $messages;
#[ORM\OneToMany(mappedBy: 'property', targetEntity: PropertyImage::class, orphanRemoval: true)]
private $propertyImages;
public function __construct()
{
$this->options = new ArrayCollection();
$this->messages = new ArrayCollection();
$this->propertyImages = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
public function getSlug(): string
{
return (new Slugify())->slugify($this->name);
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getArea(): ?int
{
return $this->area;
}
public function setArea(?int $area): self
{
$this->area = $area;
return $this;
}
public function getRooms(): ?int
{
return $this->rooms;
}
public function setRooms(?int $rooms): self
{
$this->rooms = $rooms;
return $this;
}
public function getBedrooms(): ?int
{
return $this->bedrooms;
}
public function setBedrooms(?int $bedrooms): self
{
$this->bedrooms = $bedrooms;
return $this;
}
public function getBathrooms(): ?int
{
return $this->bathrooms;
}
public function setBathrooms(?int $bathrooms): self
{
$this->bathrooms = $bathrooms;
return $this;
}
public function getPrice(): ?int
{
return $this->price;
}
public function getFormattedPrice(): string
{
return number_format($this->price, 0, '', ' ');
}
public function setPrice(?int $price): self
{
$this->price = $price;
return $this;
}
public function getFloor(): ?int
{
return $this->floor;
}
public function setFloor(?int $floor): self
{
$this->floor = $floor;
return $this;
}
public function getHeat(): ?int
{
return $this->heat;
}
public function getHeatType(): string
{
return self::HEAT[$this->heat];
}
public function setHeat(?int $heat): self
{
$this->heat = $heat;
return $this;
}
public function getCity(): ?string
{
return $this->city;
}
public function setCity(?string $city): self
{
$this->city = $city;
return $this;
}
public function getAddress(): ?string
{
return $this->address;
}
public function setAddress(?string $address): self
{
$this->address = $address;
return $this;
}
public function getCountry(): ?string
{
return $this->country;
}
public function setCountry(?string $country): self
{
$this->country = $country;
return $this;
}
public function getFullAddress(): string
{
return $this->getAddress() . ', ' . $this->getPostalCode() . ', ' . $this->getCity() . ', ' . $this->getCountry();
}
public function getSold(): ?bool
{
return $this->sold;
}
public function setSold(bool $sold): self
{
$this->sold = $sold;
return $this;
}
public function getPostalCode(): ?string
{
return $this->postalCode;
}
public function setPostalCode(?string $postalCode): self
{
$this->postalCode = $postalCode;
return $this;
}
public function getType(): ?int
{
return $this->type;
}
public function getTypeType(): string
{
return self::TYPE[$this->type];
}
public function setType(?int $type): self
{
$this->type = $type;
return $this;
}
public function getCategory(): ?int
{
return $this->category;
}
public function getCategoryType(): string
{
return self::CATEGORY[$this->category];
}
public function setCategory(?int $category): self
{
$this->category = $category;
return $this;
}
public function getGarage(): ?int
{
return $this->garage;
}
public function setGarage(?int $garage): self
{
$this->garage = $garage;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
#[ORM\PrePersist]
#[ORM\PreUpdate]
public function updateTimestamps()
{
if ($this->getCreatedAt() === null)
{
$this->setCreatedAt(new \DateTimeImmutable);
}
$this->setUpdatedAt(new \DateTimeImmutable);
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
/**
* @return Collection<int, Option>
*/
public function getOptions(): Collection
{
return $this->options;
}
public function addOption(Option $option): self
{
if (!$this->options->contains($option)) {
$this->options[] = $option;
}
return $this;
}
public function removeOption(Option $option): self
{
$this->options->removeElement($option);
return $this;
}
/**
* @return Collection<int, Message>
*/
public function getMessages(): Collection
{
return $this->messages;
}
public function addMessage(Message $message): self
{
if (!$this->messages->contains($message)) {
$this->messages[] = $message;
$message->setProperty($this);
}
return $this;
}
public function removeMessage(Message $message): self
{
if ($this->messages->removeElement($message)) {
// set the owning side to null (unless already changed)
if ($message->getProperty() === $this) {
$message->setProperty(null);
}
}
return $this;
}
/**
* @return Collection<int, PropertyImage>
*/
public function getPropertyImages(): Collection
{
return $this->propertyImages;
}
public function addPropertyImage(PropertyImage $propertyImage): self
{
if (!$this->propertyImages->contains($propertyImage)) {
$this->propertyImages[] = $propertyImage;
$propertyImage->setProperty($this);
}
return $this;
}
public function removePropertyImage(PropertyImage $propertyImage): self
{
if ($this->propertyImages->removeElement($propertyImage)) {
// set the owning side to null (unless already changed)
if ($propertyImage->getProperty() === $this) {
$propertyImage->setProperty(null);
}
}
return $this;
}
}
"
Entity Message
"<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\MessageRepository;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity(repositoryClass: MessageRepository::class)]
#[ORM\Table(name: 'messages')]
#[ORM\HasLifecycleCallbacks]
class Message
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Length(min: 3, max: 100)]
private $name;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Email(message: 'Is not a valid email.')]
private $email;
#[ORM\Column(type: 'string', length: 255)]
#[Assert\NotBlank]
#[Assert\Length(min: 3, max: 100)]
private $subject;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
#[Assert\Regex('/[0-9]/')]
#[Assert\Length(min: 5, max: 20)]
private $phone;
#[ORM\Column(type: 'text')]
#[Assert\NotBlank]
#[Assert\Length(min: 16)]
private $message;
#[ORM\ManyToOne(targetEntity: Property::class, inversedBy: 'messages')]
private $property;
#[ORM\Column(
type: 'datetime',
options: ["default" => "CURRENT_TIMESTAMP"]
)]
private $createdAt;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(?string $email): self
{
$this->email = $email;
return $this;
}
public function getSubject(): ?string
{
return $this->subject;
}
public function setSubject(?string $subject): self
{
$this->subject = $subject;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(?string $phone): self
{
$this->phone = $phone;
return $this;
}
public function getMessage(): ?string
{
return $this->message;
}
public function setMessage(?string $message): self
{
$this->message = $message;
return $this;
}
public function getProperty(): ?Property
{
return $this->property;
}
public function setProperty(?Property $property): self
{
$this->property = $property;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
#[ORM\PrePersist]
public function updateTimestamps()
{
$this->setCreatedAt(new \DateTimeImmutable);
}
}
"
MessagesController
"<?php
namespace App\Controller\BackOffice\Agent_Admin;
use App\Entity\Message;
use App\Entity\Property;
use App\Repository\MessageRepository;
use Doctrine\Persistence\ManagerRegistry;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
#[Security("is_granted('ROLE_USER') && user.isVerified()")]
#[Route('/agent-admin/messages')]
class MessagesController extends AbstractController
{
private $messageRepository;
public function __construct(MessageRepository $messageRepository)
{
$this->messageRepository = $messageRepository;
}
#[Route('', name: 'app_agent_admin_messages', methods: ['GET'])]
#[IsGranted("IS_AUTHENTICATED_FULLY")]
public function index(): Response
{
return $this->render('administration/agent_admin/messages/index.html.twig');
}
/**
* @Route("/{slug}-{id<[0-9]+>}", name="app_agent_admin_messages_property", methods={"GET"}, requirements={"slug": "[a-z0-9\-]*"})
* @IsGranted("IS_AUTHENTICATED_FULLY")
* @Security("property.getUser() == user")
*/
public function messageProperty(PaginatorInterface $paginator, Request $request, Property $property, string $slug): Response
{
if ($property->getSlug() !== $slug) {
return $this->redirectToRoute('app_agent_admin_messages', [
'id' => $property->getId(),
'slug' => $property->getSlug(),
], 301);
}
$data = $messages = $this->messageRepository->findBy(
['property' => $property],
['id' => 'DESC']
);
$messages = $paginator->paginate(
$data, /**query NOT result*/
$request->query->getInt('page', 1), /*page nomber*/
10 /*limit per page*/
);
return $this->render('administration/agent_admin/messages/messages_properties.html.twig', [
'property' => $property,
'messages' => $messages,
]);
}
#[Route('/delete/{id<[0-9]+>}', name: 'app_agent_admin_messages_delete', methods: ['GET'])]
#[IsGranted("IS_AUTHENTICATED_FULLY")]
#[Security("message.getProperty().getUser() == user")]
public function delete(Request $request, ManagerRegistry $doctrine, Message $message): Response
{
//IL FAUT UNE REQUET DE TYPE DELETE methods: ['DELETE']
$em = $doctrine->getManager();
if ($this->isCsrfTokenValid('message_deletion_' . $message->getId(), $request->query->get('csrf_token'))) {
$em->remove($message);
$em->flush();
$this->addFlash('success', 'Message deleted successfully!');
}
else{
$this->addFlash('danger', 'Action Error: Message not deleted. Invalid token!');
}
return $this->redirectToRoute('app_agent_admin_messages');
}
}"
Ce que je veux
Maintenant Je veux récupérer tous les Messages qui sont pour un User et je ne sais pas comment m'y prendre. merci de votre aide
Ce que j'obtiens
Bonjour,
La méthode simple : utiliser les getters de ton entité User pour récupérer les propriétés :
$properties = $user->getProperties();
et ensuite tu boucle sur $properties pour récupérer les messages.
Après tu pourras améliorer les perfs en faisant un méthode dans le repository et en utilisant des jointures.
Hello les devs...
Mon problème est définitivement résolu
Merci à gillesr qui m'a ouvert l'esprit
Voici l'amélioration apportée :
Dans le messageRepository:
"
public function findAllMessagesFromAnAgent($userId)
{
$query = $this->createQueryBuilder('m')
->select('p', 'm')
->join('m.property', 'p')
->andWhere('p.user = :val')
->setParameter('val', $userId)
->orderBy('m.id', 'DESC');
return $query->getQuery()->getResult();
;
}
"
Dans mon controller je récupère l'Id de l'User concerné: dans mon cas User connecté:
"
public function index(): Response
{
//Id de l'User concerné
$userId = $this->getUser()->getId();
$messages = $this->messageRepository->findAllMessagesFromAnAgent($userId);
return $this->render('administration/agent_admin/messages/index.html.twig', [
'messages' => $messages,
]);
}
"