我有2个实体,用户和课程,每个学生都可以有很多课程,每个课程都可以有很多学生。无论如何,我正在尝试做到这一点,以便当用户连接到他的帐户时,它向他展示了与他相关的所有课程。我知道我必须从控制器中做到这一点,但是我只能得到他与之相关的人。我的实体
<?php
/**
* @ORMEntity
*/
class User implements UserInterface
{
/**
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
/**
* @ORMManyToMany(targetEntity="AppEntityCourses", mappedBy="Users")
*/
private $courses;
public function __construct()
{
$this->courses = new ArrayCollection();
}
/**
* @return Collection|course[]
*/
public function getCourses(): Collection
{
return $this->courses;
}
public function addCourse(Course $course): self
{
if (!$this->courses->contains($course)) {
$this->courses[] = $course;
$course->addUser($this);
return $this;
}
return $this;
}
public function removeCourse(Course $course): self
{
if ($this->courses->contains($course)) {
$this->courses->removeElement($course);
$course->removeUser($this);
}
return $this;
}
}
<?php
/**
* @ORMEntity(repositoryClass="AppRepositoryCourseRepository")
*/
class Course
{
/**
* @ORMId()
* @ORMGeneratedValue()
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=55)
*/
private $name;
/**
* @ORMManyToMany(targetEntity="AppEntityuser", inversedBy="courses")
*/
private $users;
public function __construct()
{
$this->users = 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|user[]
*/
public function getUser(): Collection
{
return $this->user;
}
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;
}
}
好吧,因为您显然有双向关系(反向和mappedby(,您无需做任何特别的事情。学说已经做到了。只需在控制器中抓住用户:
// Once you have a protected controller route,
// you can use $this->getUser() from inside the
// controller action to access the current authenticated user.
$user = $this->getUser();
和您想要通过他们的相关课程的迭代:
foreach ($user->getCourses() as $course) {
}
因为getCourses
还返回了Collection
实例,因此您还可以使用->map
和->filter
函数,该功能与收集类一起运送...