I have two entities, Classe and students, the class has a OneToMany relation with Student as one class can have many students.
I'm creating a page where I show the names of all the students related to a chosen classes and I can't access the data in students from Classe.
entity class
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\ClasseRepository")
*/
class Classe
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=200)
*/
private $label;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Student", mappedBy="classe", orphanRemoval=true)
*/
private $Students;
/**
* #ORM\OneToMany(targetEntity="App\Entity\WorkDays", mappedBy="class")
*/
private $schedule;
public function __construct()
{
$this->Students = new ArrayCollection();
$this->schedule = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
/**
* #return Collection|Student[]
*/
public function getStudents(): Collection
{
return $this->Students;
}
public function addStudent(Student $student): self
{
if (!$this->Students->contains($student)) {
$this->Students[] = $student;
$student->setClasse($this);
}
return $this;
}
public function removeStudent(Student $student): self
{
if ($this->Students->contains($student)) {
$this->Students->removeElement($student);
// set the owning side to null (unless already changed)
if ($student->getClasse() === $this) {
$student->setClasse(null);
}
}
return $this;
}
/**
* #return Collection|WorkDays[]
*/
public function getSchedule(): Collection
{
return $this->schedule;
}
public function addSchedule(WorkDays $schedule): self
{
if (!$this->schedule->contains($schedule)) {
$this->schedule[] = $schedule;
$schedule->setClass($this);
}
return $this;
}
public function removeSchedule(WorkDays $schedule): self
{
if ($this->schedule->contains($schedule)) {
$this->schedule->removeElement($schedule);
// set the owning side to null (unless already changed)
if ($schedule->getClass() === $this) {
$schedule->setClass(null);
}
}
return $this;
}
}
Entity Student
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\StudentRepository")
*/
class Student
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=200)
*/
private $firstname;
/**
* #ORM\Column(type="string", length=200)
*/
private $lastname;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\classe", inversedBy="Students")
* #ORM\JoinColumn(nullable=false)
*/
private $classe;
public function getId(): ?int
{
return $this->id;
}
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 getClasse(): ?classe
{
return $this->classe;
}
public function setClasse(?classe $classe): self
{
$this->classe = $classe;
return $this;
}
}
As I said before, a class can have many students and I need to get the names of the students that a related to that class and put them in a list.
Because the entities are related to eachother you can access the student info of a class through the Entity Classe or the other way arround. For example:
Controller:
namespace App\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class ClasseController extends AbstractController {
/**
* #Route("/{id}", name="index", methods={"GET"})
*/
public function index(ClasseRepository $repository, $id) {
return $this->render('index.html.twig', [
'students' => $repository->getStudents($id),
]);
}
Repository:
namespace App\Repository;
use App\Entity\Classe;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
class ClasseRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Classe::class);
}
public function getStudents($id) {
return $this->createQueryBuilder('c')
->select('c.Students')
->andWhere('c.id = :id')
->setParameter('id', $id)
->getQuery()
->getResult()
;
}
}
Related
I have a OneToMany relationship on these 2 entities:
Article
ArticleLikes
<?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=255)
*/
private $title;
/**
* #ORM\Column(type="text")
*/
private $content;
/**
* #ORM\Column(type="datetime_immutable")
*/
private $createdAt;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="articles")
* #ORM\JoinColumn(nullable=false)
*/
private $relation;
/**
* #ORM\OneToMany(targetEntity=ArticleLikes::class, mappedBy="article")
*/
private $articleLikes;
public function __construct()
{
$this->articleLikes = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getRelation(): ?User
{
return $this->relation;
}
public function setRelation(?User $relation): self
{
$this->relation = $relation;
return $this;
}
/**
* #return Collection|ArticleLikes[]
*/
public function getArticleLikes(): Collection
{
return $this->articleLikes;
}
public function addArticleLike(ArticleLikes $articleLike): self
{
if (!$this->articleLikes->contains($articleLike)) {
$this->articleLikes[] = $articleLike;
$articleLike->setArticle($this);
}
return $this;
}
public function removeArticleLike(ArticleLikes $articleLike): self
{
if ($this->articleLikes->removeElement($articleLike)) {
// set the owning side to null (unless already changed)
if ($articleLike->getArticle() === $this) {
$articleLike->setArticle(null);
}
}
return $this;
}
/**
* #param User $user
* #return bool
*/
public function isLikedByUser(User $user): bool
{
foreach ($this->getArticleLikes() as $like)
{
if ($like->getUser() === $user) {
return true;
}
}
return false;
}
}
<?php
namespace App\Entity;
use App\Repository\ArticleLikesRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=ArticleLikesRepository::class)
*/
class ArticleLikes
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=Article::class, inversedBy="articleLikes")
* #ORM\JoinColumn(nullable=false)
*/
private $article;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="articleLikes")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #ORM\Column(type="datetime_immutable")
*/
private $createdAt;
public function getId(): ?int
{
return $this->id;
}
public function getArticle(): ?Article
{
return $this->article;
}
public function setArticle(?Article $article): self
{
$this->article = $article;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
}
The Article entity can contain a collection of ArticleLikes.
In the ArticleLikes entity, each like is related to an Article (articleId) as well as to a user field (userId).
To retrieve the number of likes for each article, I have a method in the Article entity:
/ **
* #return Collection | ArticleLikes []
* /
public function getArticleLikes (): Collection
{
return $ this-> articleLikes;
}
I am lost because I would like to create a query that allows you to retrieve the last 10 articles the most liked (with the most of ArticleLikes). I don't know if I need to do a left join or something else. How can I do this query?
I want to retrieve the 10 articles that have the most ArticleLikes.
Image:
The solution was to put:
->orderBy('count(al)', 'DESC')
Query Builder that gets the 10 most liked articles:
/**
* #return array
* get the 10 most liked articles
*/
public function findArticlesMostLiked(): array
{
return $this->createQueryBuilder('a')
->select( 'a')
->join('a.articleLikes', 'al')
->groupBy('al.article')
->orderBy('count(al)', 'DESC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
i want to develop a doctrine-powered database application which should portray the following schema.
There are users, companies and relation-roles which describes the relation between a user to a company like [USER X] is [ROLE X] in [COMPANY X].
I'm using the symfony maker-bundle to create the entities I need. I'll attach every code at the end of this post.
To test the code, I persisted a company, a user, a role and a relation between them to the database. I expected that I could get all related users with their roles using a Company-Entity-Object with the generated getter getRelatedUsers() but I get an empty ArrayCollection.
This is how I tested to fetch the data in a TestController
#[Route('/test', name: 'test_page')]
public function index(CompanyRepository $companyRepository): Response
{
$companies = $companyRepository->findAll();
dd($companies[0]->getRelatedUsers());
}
Thanks for your help!
User.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;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #ORM\Table(name="`user`")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $fullName;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="user")
*/
private $relatedCompanies;
public function __construct()
{
$this->relatedCompanies = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getFullName(): ?string
{
return $this->fullName;
}
public function setFullName(string $fullName): self
{
$this->fullName = $fullName;
return $this;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getRelatedCompanies(): Collection
{
return $this->relatedCompanies;
}
public function addRelatedCompany(UserCompanyRelation $relatedCompany): self
{
if (!$this->relatedCompanies->contains($relatedCompany)) {
$this->relatedCompanies[] = $relatedCompany;
$relatedCompany->setUser($this);
}
return $this;
}
public function removeRelatedCompany(UserCompanyRelation $relatedCompany): self
{
if ($this->relatedCompanies->removeElement($relatedCompany)) {
// set the owning side to null (unless already changed)
if ($relatedCompany->getUser() === $this) {
$relatedCompany->setUser(null);
}
}
return $this;
}
}
Company.php
<?php
namespace App\Entity;
use App\Repository\CompanyRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=CompanyRepository::class)
*/
class Company
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="company")
*/
private $relatedUsers;
public function __construct()
{
$this->relatedUsers = 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;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getRelatedUsers(): Collection
{
return $this->relatedUsers;
}
public function addRelatedUser(UserCompanyRelation $relatedUser): self
{
if (!$this->relatedUsers->contains($relatedUser)) {
$this->relatedUsers[] = $relatedUser;
$relatedUser->setCompany($this);
}
return $this;
}
public function removeRelatedUser(UserCompanyRelation $relatedUser): self
{
if ($this->relatedUsers->removeElement($relatedUser)) {
// set the owning side to null (unless already changed)
if ($relatedUser->getCompany() === $this) {
$relatedUser->setCompany(null);
}
}
return $this;
}
}
UserCompanyRelation.php
<?php
namespace App\Entity;
use App\Repository\UserCompanyRelationRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserCompanyRelationRepository::class)
*/
class UserCompanyRelation
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=UserCompanyRelationRole::class, inversedBy="userCompanyRelations")
* #ORM\JoinColumn(nullable=false)
*/
private $role;
/**
* #ORM\ManyToOne(targetEntity=Company::class, inversedBy="relatedUsers")
* #ORM\JoinColumn(nullable=false)
*/
private $company;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="relatedCompanies")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
public function __construct()
{
}
public function getId(): ?int
{
return $this->id;
}
public function getRole(): ?UserCompanyRelationRole
{
return $this->role;
}
public function setRole(?UserCompanyRelationRole $role): self
{
$this->role = $role;
return $this;
}
public function getCompany(): ?Company
{
return $this->company;
}
public function setCompany(?Company $company): self
{
$this->company = $company;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
UserCompanyRelationRole.php
<?php
namespace App\Entity;
use App\Repository\UserCompanyRelationRoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserCompanyRelationRoleRepository::class)
*/
class UserCompanyRelationRole
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="role")
*/
private $userCompanyRelations;
public function __construct()
{
$this->userCompanyRelations = 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;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getUserCompanyRelations(): Collection
{
return $this->userCompanyRelations;
}
public function addUserCompanyRelation(UserCompanyRelation $userCompanyRelation): self
{
if (!$this->userCompanyRelations->contains($userCompanyRelation)) {
$this->userCompanyRelations[] = $userCompanyRelation;
$userCompanyRelation->setRole($this);
}
return $this;
}
public function removeUserCompanyRelation(UserCompanyRelation $userCompanyRelation): self
{
if ($this->userCompanyRelations->removeElement($userCompanyRelation)) {
// set the owning side to null (unless already changed)
if ($userCompanyRelation->getRole() === $this) {
$userCompanyRelation->setRole(null);
}
}
return $this;
}
}
I found an solution. I had to modify the fetch-strategy to EAGER in a annotation attribute. I modified the relatedUsers annotation property in company.php
<?php
namespace App\Entity;
use App\Repository\CompanyRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=CompanyRepository::class)
*/
class Company
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=UserCompanyRelation::class, mappedBy="company", fetch="EAGER")
*/
private $relatedUsers;
public function __construct()
{
$this->relatedUsers = 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;
}
/**
* #return Collection|UserCompanyRelation[]
*/
public function getRelatedUsers(): Collection
{
return $this->relatedUsers;
}
public function addRelatedUser(UserCompanyRelation $relatedUser): self
{
if (!$this->relatedUsers->contains($relatedUser)) {
$this->relatedUsers[] = $relatedUser;
$relatedUser->setCompany($this);
}
return $this;
}
public function removeRelatedUser(UserCompanyRelation $relatedUser): self
{
if ($this->relatedUsers->removeElement($relatedUser)) {
// set the owning side to null (unless already changed)
if ($relatedUser->getCompany() === $this) {
$relatedUser->setCompany(null);
}
}
return $this;
}
}
You should use inversed by for bidirectional mapping between entities. See: https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/association-mapping.html#many-to-many-bidirectional
in my project i create 2 entities :Projects & category.They are a ManyToMany relation MySql shema
im using Easy-admin bundle trying to Manage my database but the problem is when i try to add a category to a project it will not save, it work when i try to add a project to a category but i don't know why it fails in the other way . thanks for help :)
Category
<?php
namespace App\Entity;
use App\Repository\CategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=CategoryRepository::class)
* #ORM\Table(name="category")
*/
class Category
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $title;
/**
* #ORM\Column(type="text")
*/
private $body;
/**
* #ORM\Column(type="string", length=255)
*/
private $image;
/**
* #ORM\Column(type="datetime")
*/
private $createdAt;
/**
* #ORM\ManyToMany(targetEntity=Projects::class, inversedBy="category",cascade={"persist"})
*
*/
private $projects;
public function __construct()
{
$this->projects = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getBody(): ?string
{
return $this->body;
}
public function setBody(string $body): self
{
$this->body = $body;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
/**
* #return Collection|projects[]
*/
public function getProjects(): Collection
{
return $this->projects;
}
public function addProjects(projects $project): self
{
if (!$this->projects->contains($project)) {
$this->projects[] = $project;
$project->addCategory($this);
}
return $this;
}
public function removeProjects(projects $project): self
{
if ($this->projects->contains($project)) {
$this->projects->removeElement($project);
$project->removeCategory($this);
}
return $this;
}
public function __toString()
{
return $this->title;
}
}
projects
<?php
namespace App\Entity;
use App\Repository\ProjectsRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=ProjectsRepository::class)
* #ORM\Table(name="projects")
*/
class Projects
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $title;
/**
*
* #ORM\Column(type="text")
*/
private $body;
/**
* #ORM\Column(type="string", length=255)
*/
private $image;
/**
* #ORM\Column(type="datetime")
*/
private $createdAt;
/**
* #ORM\ManyToMany(targetEntity=Category::class, mappedBy="projects",cascade={"persist"})
*/
private $category;
public function __construct()
{
$this->category = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getBody(): ?string
{
return $this->body;
}
public function setBody(string $body): self
{
$this->body = $body;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
/**
* #return Collection|category
*/
public function getCategory(): Collection
{
return $this->category;
}
public function addCategory(category $category): self
{
if (!$this->category->contains($category)) {
$this->category[] = $category;
$category->addProjects($this);
}
return $this;
}
public function removeCategory(Category $category): self
{
if ($this->category->contains($category)) {
$this->category->removeElement($category);
$category->removeProjects($this);
}
return $this;
}
public function __toString()
{
return $this->title;
}
}
I suspect, that the adders and removers are never called. In the case of Category::getProjects you return the collection, which, when changed, will lead to updates in the database, since it's the owning side of the relation.
On the other side however, you got Projects::getCategory, which also returns the collection, which probably is modified, but the changes are not propagated to the database at all, since it's the inverse side.
To fix this, I presume you have to fix your pluralization:
Category's property should be called $projects, the getter should be called getProjects and imho return $this->projects->toArray(); (the implementation details should be hidden), the adder should be named addProject (note the missing s) and the remover removeProject. Symfony will handle the different pluralizations and understand which methods to call.
the class should be called Project (no plural s) and similarly the getters, adders and removers have their names getCategories, addCategory and removeCategory. again, in the getter return $this->categories->toArray(). providing the collection might lead to the bundle editing the collection directly, especially if the adders and removers are named weirdly.
After these changes (adapting the #ManyToMany annotations too of course), it should work (tm).
it worked the mapping was false it should be like this in
category
#ORM\ManyToMany(targetEntity=Projects::class, mappedBy="categories")
and like this in projects
#ORM\ManyToMany(targetEntity=Category::class, inversedBy="projects")
then i droped the db and update the schema ... plus the fix of the pluralization
thnx a lot <3 <3
I have a user entity that has a many-to-many relationship with another entity Roles.
I have a form that allows me to create a new user and for that, I use an EntityType for the manyToMany relationship 'roles'.
Here is my form
$builder
->add('username',null,['label' => 'Email'])
->add('password',null,['label'=>'Password'])
->add('roles',EntityType::class, [
'multiple' => true,
'class' => Role::class,
'choice_label' => 'role_name',
]
)
;
Everything works fine but when I submit the form I got this error:
Expected argument of type "App\Entity\Role", "string" given at
property path "roles".
EDIT:
here is my User entity :
<?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\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $username;
/**
* #ORM\Column(type="string", length=255)
*/
private $password;
/**
* #ORM\ManyToMany(targetEntity=Role::class, inversedBy="users")
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getRoles()
{
return ['ROLE_ADMIN'];
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
public function addRole(Role $role): self
{
if (!$this->roles->contains($role)) {
$this->roles[] = $role;
$role->addUser($this);
}
return $this;
}
public function removeRole(Role $role): self
{
if ($this->roles->contains($role)) {
$this->roles->removeElement($role);
$role->removeUser($this);
}
return $this;
}
}
Here is my Role entity :
<?php
namespace App\Entity;
use App\Repository\RoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=RoleRepository::class)
*/
class Role
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $role_name;
/**
* #ORM\ManyToMany(targetEntity=User::class, mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRoleName(): ?string
{
return $this->role_name;
}
public function setRoleName(string $role_name): self
{
$this->role_name = $role_name;
return $this;
}
/**
* #return Collection|User[]
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->contains($user)) {
$this->users->removeElement($user);
}
return $this;
}
}
I guess the problem is here
public function getRoles()
{
return ['ROLE_ADMIN'];
}
you should return an array or Role entity not string, it should be something like this
public function getRoles()
{
return $this->roles;
}
what if i'm using ArrayCollection in User entity?
/**
* #var Collection|Role[]
* #ORM\ManyToMany(targetEntity="App\Entity\Role")
* #ORM\JoinTable(
* name="user_roles",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getRoles()
{
return $this->roles;
}
After looking over the internet and here I didn' find something useful for me.
I'm currently creating a CRUD. Every 'Entreprise' having one or multiple 'Site' and I'm currently doing the CRUD for Site. I've made it by doing the make:form command.
Whhen I'm going to create a site the following error appear :
Catchable Fatal Error: Object of class App\Entity\Entreprise could not
be converted to string
I've tried to add the function __toString() as i saw. But maybe i didn't add it crrectly it changes nothing so I removed it.
My controller to create a site looks like this :
/**
* #Route("admin/sites/new", name="admin.sites.new")
* #param Request $request
* #return RedirectResponse|Response
*/
public function new (Request $request)
{
$site = new Site();
$form = $this->createForm(SiteType::class, $site);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$this->em->persist($site);
$this->em->flush();
$this->addFlash('success', 'Site crée avec succès');
return $this->redirectToRoute('admin.sites.index');
}
return $this->render('admin/sites/create.html.twig', [
'site' => $site,
'form' => $form->createView()
]);
}
}
My SiteType generate by the make:form commande :
/**
* #Route("admin/sites/new", name="admin.sites.new")
* #param Request $request
* #return RedirectResponse|Response
*/
public function new (Request $request)
{
$site = new Site();
$form = $this->createForm(SiteType::class, $site);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$this->em->persist($site);
$this->em->flush();
$this->addFlash('success', 'Site crée avec succès');
return $this->redirectToRoute('admin.sites.index');
}
return $this->render('admin/sites/create.html.twig', [
'site' => $site,
'form' => $form->createView()
]);
}
}
So here are my ENTITY
Entreprise
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\EntrepriseRepository")
*/
class Entreprise
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_nom;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_siret;
/**
* #ORM\Column(type="string", length=10)
*/
private $entreprise_telephone;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_salesforce_number;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_compte_client;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_raison_sociale;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_APE;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $entreprise_image_link;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Site", mappedBy="entreprise_id")
*/
private $entreprise_id;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Catalogue", mappedBy="entreprise_id")
*/
private $entreprise_catalogue_id;
public function __construct()
{
$this->entreprise_id = new ArrayCollection();
$this->entreprise_catalogue_id = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEntrepriseNom(): ?string
{
return $this->entreprise_nom;
}
public function setEntrepriseNom(string $entreprise_nom): self
{
$this->entreprise_nom = $entreprise_nom;
return $this;
}
public function getEntrepriseSiret(): ?string
{
return $this->entreprise_siret;
}
public function setEntrepriseSiret(string $entreprise_siret): self
{
$this->entreprise_siret = $entreprise_siret;
return $this;
}
public function getEntrepriseTelephone(): ?int
{
return $this->entreprise_telephone;
}
public function setEntrepriseTelephone(int $entreprise_telephone): self
{
$this->entreprise_telephone = $entreprise_telephone;
return $this;
}
public function getEntrepriseSalesforceNumber(): ?string
{
return $this->entreprise_salesforce_number;
}
public function setEntrepriseSalesforceNumber(string $entreprise_salesforce_number): self
{
$this->entreprise_salesforce_number = $entreprise_salesforce_number;
return $this;
}
public function getEntrepriseCompteClient(): ?string
{
return $this->entreprise_compte_client;
}
public function setEntrepriseCompteClient(string $entreprise_compte_client): self
{
$this->entreprise_compte_client = $entreprise_compte_client;
return $this;
}
public function getEntrepriseRaisonSociale(): ?string
{
return $this->entreprise_raison_sociale;
}
public function setEntrepriseRaisonSociale(string $entreprise_raison_sociale): self
{
$this->entreprise_raison_sociale = $entreprise_raison_sociale;
return $this;
}
public function getEntrepriseAPE(): ?string
{
return $this->entreprise_APE;
}
public function setEntrepriseAPE(string $entreprise_APE): self
{
$this->entreprise_APE = $entreprise_APE;
return $this;
}
public function getEntrepriseImageLink(): ?string
{
return $this->entreprise_image_link;
}
public function setEntrepriseImageLink(?string $entreprise_image_link): self
{
$this->entreprise_image_link = $entreprise_image_link;
return $this;
}
/**
* #return Collection|Site[]
*/
public function getEntrepriseId(): Collection
{
return $this->entreprise_id;
}
public function addEntrepriseId(Site $entrepriseId): self
{
if (!$this->entreprise_id->contains($entrepriseId)) {
$this->entreprise_id[] = $entrepriseId;
$entrepriseId->setEntrepriseId($this);
}
return $this;
}
public function removeEntrepriseId(Site $entrepriseId): self
{
if ($this->entreprise_id->contains($entrepriseId)) {
$this->entreprise_id->removeElement($entrepriseId);
// set the owning side to null (unless already changed)
if ($entrepriseId->getEntrepriseId() === $this) {
$entrepriseId->setEntrepriseId(null);
}
}
return $this;
}
}
And here is
Site
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\SiteRepository")
*/
class Site
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $site_nom;
/**
* #ORM\Column(type="string", length=255)
*/
private $site_raison_sociale;
/**
* #ORM\Column(type="string", length=255)
*/
private $site_APE;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Client", mappedBy="site_id")
*/
private $site_id;
/**
* #ORM\OneToOne(targetEntity="App\Entity\Adresse", cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $adresse_id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Entreprise", inversedBy="entreprise_id")
* #ORM\JoinColumn(nullable=false)
*/
private $entreprise_id;
public function __construct()
{
$this->site_id = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getSiteNom(): ?string
{
return $this->site_nom;
}
public function setSiteNom(string $site_nom): self
{
$this->site_nom = $site_nom;
return $this;
}
public function getSiteRaisonSociale(): ?string
{
return $this->site_raison_sociale;
}
public function setSiteRaisonSociale(string $site_raison_sociale): self
{
$this->site_raison_sociale = $site_raison_sociale;
return $this;
}
public function getSiteAPE(): ?string
{
return $this->site_APE;
}
public function setSiteAPE(string $site_APE): self
{
$this->site_APE = $site_APE;
return $this;
}
/**
* #return Collection|Client[]
*/
public function getSiteId(): Collection
{
return $this->site_id;
}
public function addSiteId(Client $siteId): self
{
if (!$this->site_id->contains($siteId)) {
$this->site_id[] = $siteId;
$siteId->addSiteId($this);
}
return $this;
}
public function removeSiteId(Client $siteId): self
{
if ($this->site_id->contains($siteId)) {
$this->site_id->removeElement($siteId);
$siteId->removeSiteId($this);
}
return $this;
}
public function getAdresseId(): ?Adresse
{
return $this->adresse_id;
}
public function setAdresseId(Adresse $adresse_id): self
{
$this->adresse_id = $adresse_id;
return $this;
}
public function getEntrepriseId(): ?Entreprise
{
return $this->entreprise_id;
}
public function setEntrepriseId(?Entreprise $entreprise_id): self
{
$this->entreprise_id = $entreprise_id;
return $this;
}
public function __toString()
{
return $this->getSiteNom();
}
}
I didn't know what's wrong. Maybe the __toString I didn't write correclty !
I've wrote :
public function __toString()
{
return $this->getSiteNom();
}
}
Catchable Fatal Error: Object of class App\Entity\Entreprise
You need to implement the __toString() method in the Entreprise entity
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\EntrepriseRepository")
*/
class Entreprise
{
//...
public function __toString()
{
return $this->entreprise_nom;
}
// ...
}