1

I have 3 tables namely A, B and C. All 3 of them need to make use of a notes table(i.e. A has many notes and a note belongs to A. The same follows for remaining 2 tables).
So I created 3 more tables: A_note, B_note and C_note(as mentioned here: multiple tables need one to many relationship).

Is there a way to do CRUD operations on these tables(A_note, B_note and C_note) similar to the way we handle pivot table in many-to-many relationship?

Please suggest a way forward.

Community
  • 1
  • 1
Shyam
  • 37
  • 1
  • 8

1 Answers1

1

You should be using polymorphic relationships for this. It allows multiple models to make use of a single table.

Have a look at the documentation here

In your particular case, each of your tables would reference a noteable_id column and a noteable_type.

The noteable_id will contain the id of the (A/B/C) model.

The noteable_type will contain the string name of the model (A/B/C).

The (A/B/C) models will now get a new attribute:

/**
 * (A/B/C) Model(s)
 */
public function notes()
{
    return $this->morphMany('App\Notes', 'noteable');
}

And the note model will initiate it's polymorphic properties against the attribute name used to identify your polymorphic ids and types:

/**
 * Note Model
 */
public function noteable()
{
    return $this->morphTo();
}

Now you can simply call ->noteable on the (A/B/C) models, and they all share 1 table without the need of another pivot table for each table.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110