Creating a one to many polymorphic relationship with doctrine

前端 未结 5 2359
猫巷女王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:09

    I add another answer after reading your question once more and realizing that you stated "I want to avoid adding another join table".

    Make a Note base entity and extend this class in 3 different note entities for example: BookNote, AddressNote and ImageNote. In my solution the note table would look like this:

    id | address_id | book_id | image_id | object_type | content      | date
    1  | null       | null    | 1        | image       | "lovely pic" | 2015-02-10
    2  | null       | null    | 1        | image       | "red tint"   | 2015-02-30
    3  | 1          | null    | null     | address     | "invalid"    | 2015-01-05
    4  | null       | 2       | null     | book        | "boobies"    | 2014-09-06
    5  | null       | 1       | null     | book        | "prettygood" | 2016-05-05
    

    You cannot use one common column object_id because of the foreign key constraints.

    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 Note entity:

    Your BookNote entity:

    Your AddressNote entity:

    Your ImageNote entity:

    Your Book entity:

    notes = new ArrayCollection();
        }
    }
    

    Your Address entity:

    notes = new ArrayCollection();
        }
    }
    

    Your Image entity:

    notes = new ArrayCollection();
        }
    }
    

提交回复
热议问题