简体   繁体   中英

Getting values from related tables

I'm trying to find a route in which there are 2 cities. I have tables "route", "city" and "route_city". On input i have two city ids(from and to). My tables:

city

id name
1  Kiev
2  Rome

route

id name
1  Kiev-Rome
2  Rome-Kiev

route_city

id route_id city_id sort
1         1        1   1
2         1        2   2
3         2        2   1
4         2        1   2

I tried:

SELECT `route_id` FROM `route_city` WHERE (`route_city`.`city_id` IN ('1', '2')) GROUP BY `route_city`.`route_id`

If i have from=Kiev and to=Rome, i get both routes.

1)How i can get only one route?

2)And how i can create this query in Yii2 Framework with ActiveRecord?

is the sort column your code for from and to ? Like this: if sort=1, it's from and if sort=2, it's to ?

If yes, to do from=Kiev and to=Rome you can do :

SELECT `route_id` FROM `route_city` WHERE (`route_city`.`city_id` IN ('1', '2')) AND `route_city`.`sort`=1 GROUP BY `route_city`.`route_id`

For Yii I can't be of any help !

Cant find route with this table structure. Need to get it from another table or change structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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