I have 2 tables named "cred_pathway" and "course". They have a Many To Many relationship.
I defined the relationship in annotations as below.
/**
* @var Course[]|ArrayCollection
*
* @ORM\ManyToMany(targetEntity="Course\Entity\Course", inversedBy="cred_pathway")
* @ORM\JoinTable(name="cred_pathway_course",
* joinColumns={
* @ORM\JoinColumn(name="cred_pathway_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="course_id", referencedColumnName="id")
* }
* )
*/
private $credPathwayCourse;
I want to add a new course to the list if the course is not already available in the list.
public function addCourse(Course $course) {
if (!$this->credPathwayCourse->contains($course)) {
$this->credPathwayCourse->add($course);
}
}
But the problem is that $this->credPathwayCourse
contains an array in runtime and it throws the below array because I am trying to access contains()
function on an array.
Call to a member function contains() on array
Is there a way to make sure that $this->credPathwayCourse
contains a Collection or an ArrayCollection?
You can typehint it like so:
private Collection $credPathwayCourse;
Then create a constructor to ensure that your property is set using the correct collection type:
public function __construct() {
$this->credPathwayCourse = new ArrayCollection;
}
Note that an ArrayCollection
implements the Collection
interface, so if you decide that you want to use a different collection type down the road, you can just swap it out in your constructor.