Creating a one to many polymorphic relationship with doctrine

前端 未结 5 2345
猫巷女王i
猫巷女王i 2021-02-18 23:37

Let me start by outlining the scenario. I have a Note object that can be assigned to many different objects

  • A Book can have one or moreNot
5条回答
  •  我寻月下人不归
    2021-02-19 00:06

    The closest you can get is by using a unidirectional One-To-Many with a join table. In doctrine this is done with a unidirectional Many-To-Many with a unique constraint on the join column.

    The disadvantage of this solution is that it is unidirectional meaning that your note is not aware of the owning side of the relationship. But at first glance it looks like this should not be a problem in your case. You will lose the object_id and object_type column in the note table.

    In full code this would look like this:

    A NotesTrait with setters and getters for notes to prevent code duplication:

    notes[] = $note;
    
            return $this;
        }
    
        /**
         * Add notes.
         *
         * @param Collection $notes
         * @return self
         */
        public function addNotes(Collection $notes)
        {
            foreach ($notes as $note) {
                $this->addNote($note);
            }
            return $this;
        }
    
        /**
         * Remove note.
         *
         * @param Note $note
         */
        public function removeNote(Note $note)
        {
            $this->notes->removeElement($note);
        }
    
        /**
         * Remove notes.
         *
         * @param Collection $notes
         * @return self
         */
        public function removeNotes(Collection $notes)
        {
            foreach ($notes as $note) {
                $this->removeNote($note);
            }
            return $this;
        }
    
        /**
         * Get notes.
         *
         * @return Collection
         */
        public function getNotes()
        {
            return $this->notes;
        }
    }
    

    Your Book entity:

    notes = new ArrayCollection();
        }
    }
    

    Your Address entity:

    notes = new ArrayCollection();
        }
    }
    

    Your Image entity:

    notes = new ArrayCollection();
        }
    }
    

提交回复
热议问题