简体   繁体   English

市所属直辖县到省协会,代码如何简化?

[英]City belongsThroughCountyTo Province association, how to simplify the code?

Tables: 表格:

Province hasMany County , County belongsTo Province , County hasMany City , City belongsTo County Province hasMany CountyCounty belongsTo ProvinceCounty hasMany CityCity belongsTo County

So basically something like: City belongsThroughCountyTo Province 所以基本上像这样: City belongsThroughCountyTo Province

Situation: 情况:

In a search form I have a select drop down menu with provinces. 在搜索表单中,我有一个带有省份的选择下拉菜单。

The "code": 编码”:

When I list the results, I first get ids of counties that belong to the specified province, and then do a City.county_id IN (array_of_counties_ids_here) . 列出结果时,我首先获取属于指定省的县的ID,然后执行City.county_id IN (array_of_counties_ids_here)

Question: 题:

My question is, could I be doing it in a better way? 我的问题是,我可以做得更好吗? Without first accessing the counties table. 无需先访问县表。 A simple three way join should do the trick, but I don't have an idea on how to implement it in Cake. 一个简单的三种方式的联接应该可以解决问题,但是我对如何在Cake中实现它一无所知。

Adding a province_id field to the cities table isn't a solution in my case (can't alter tables). 在我的情况下,将province_id字段添加到citys表不是解决方案(无法更改表)。

You should avoid this by creating a view in SQL that directly links City to Province. 您应该通过在SQL中创建直接将城市链接到省的视图来避免这种情况。

Assuming you've got: 假设您已经:

tblCity
  city_id
  county_id
  name --etc
tblCounty
  county_id
  province_id
  name --whatever else
tblProvince
  province_id
  --whatever else

create or replace view CityToProvince as 
  select c.city_id, p.province_id from tblCity c
  join tblCounty co on co.county_id = c.county_id
  join tblProvince p on p.province_id = co.province_id;

Once that is created, you can: 创建完成后,您可以:

select province_id from CityToProvince where city_id = [whatever];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM