代码之家  ›  专栏  ›  技术社区  ›  Dula

如何确保参数在Symfony中包含Collection或ArrayCollection[复制]

  •  -1
  • Dula  · 技术社区  · 12 月前

    我有两个名为“cred_pathy”和“course”的表。他们有一种多对多的关系。

    我在注释中定义了这种关系,如下所示。

    /**
     * @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;
    

    如果列表中没有新课程,我想将其添加到列表中。

     public function addCourse(Course $course) {
        if (!$this->credPathwayCourse->contains($course)) {
            $this->credPathwayCourse->add($course);
        }
    }
    

    但问题是 $this->credPathwayCourse 在运行时包含一个数组,它抛出以下数组,因为我正在尝试访问 contains() 数组上的函数。

    调用数组上的成员函数contains()

    有没有办法确保 $这个->credPathway课程 包含集合还是数组集合?

    1 回复  |  直到 12 月前
        1
  •  -1
  •   maiorano84    12 月前

    你可以这样键入提示:

    private Collection $credPathwayCourse;
    

    然后创建一个构造函数,以确保使用正确的集合类型设置属性:

    public function __construct() {
        $this->credPathwayCourse = new ArrayCollection;
    }
    

    请注意,a ArrayCollection 实现 Collection 接口,所以如果你决定以后要使用不同的集合类型,你可以在构造函数中把它换掉。

    推荐文章