Relationship between 3 tables

独自空忆成欢 提交于 2019-12-13 06:38:58

问题


I have a mysql DB with 3 tables:

- Campaigns
 id
 code
 name

- Columns
 id
 name

- Values
 id
 idColumn
 value

The relationship beetween Campaigns and Columns is many to many:

- ColumnsCampaign
 id
 idColumn
 idCampaign

and the relationship beetween Columns and Values is one to many.

I have this query that returns all values for each campaign:

return Campaigns::addSelect('id','code','name')
->whereHas('typeCampaign', function ($q) use ($idTypeCampaign,$idMenu)
{
    $q->where('typeCampaign.id',$idTypeCampaign)
        ->whereHas('menus', function ($q) use ($idMenu){
             $q->where('menus.id',$idMenu);
        });
})//this part define which campaign i want with a certain menu
->with('columns.values')//with this i include the campaign columns and its values
->get();

My problem is that if i have different values for the same column i dont know to which campaign is associated. How can i solve this issue? Is it correct to create a relationship table between campaigns and values?


回答1:


It seems that the structure of the designed tables is not matching to its underlying domain.

If mutliple values can be assigned to a given column id (idColumn), then either an extra key field (which is actually a campaignId) is required to be introduced in table Values or create an extra table that associates campaig id, columns id and values id. The third option -this is what I recommned actually - is to unify the table Columns and Values.




回答2:


This isn't (yet?) an answer but it might be a little more obvious to the rest of us if the structure was more like this:

Campaigns
campaign_id *
code
name

Columns
column_id *
name

campaigns_columns
Campaign_id *
Column_id *

* = (component of) PRIMARY KEY



来源:https://stackoverflow.com/questions/30371161/relationship-between-3-tables

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