Multiple tables with one to many relationship(Laravel)

こ雲淡風輕ζ 提交于 2019-12-11 04:48:17

问题


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.


回答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.



来源:https://stackoverflow.com/questions/37931477/multiple-tables-with-one-to-many-relationshiplaravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!