cakephp多表级联查询

daxiongshishen 2010-12-30 12:08:31
刚开始学cakephp 问题如下: 一个搜索页面 需要填入 出发城市,和目的城市,
然后根据出发城市和目的城市搜索出2个城市的航班信息! 一共有3个表!
1:cities(城市)表
2:airports(机场)表
3:flights(航班)表

城市跟机场关联(一对多),机场跟航班关联(一对多,有出发的机场,和到达的机场)
我分了2次查询 才得到结果 先通过出发城市和目的城市查询出发机场和目的机场,然后再2个机场查询出相应的航班

之前用一次级联查询的,但是提示说 Unknown column 'fromairport.city.cityname',代码如下:
$this->Flight->find('first',
array('conditions' => array('fromairport.city.cityname' => $from_city, 'toairport.city.cityname'=>$to_city),
'recursive' =>3
));

各位老鸟们,帮小弟解决下啊!如果分2次查的话 感觉有点不方便和专业啊。。。


...全文
392 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
你的选择H 2011-01-03
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 ihefe 的回复:]
SQL code

select a.flight_name,b.airport_name,c.airport_name from flights a
join airports b on b.id=a.from_airport_id
join airports c on c.id=a.to_airport_id
join cities d on b.city_id=d.id
jo……
[/Quote]

这个应该是正确的
ihefe 2010-12-30
  • 打赏
  • 举报
回复

select a.flight_name,b.airport_name,c.airport_name from flights a
join airports b on b.id=a.from_airport_id
join airports c on c.id=a.to_airport_id
join cities d on b.city_id=d.id
join cities e on c.city_id=e.id
where b.airport_name='浦东机场' and c.airport_name='首都机场'

//用sql 一步搞定

lazysmile 2010-12-30
  • 打赏
  • 举报
回复
由于你所求的结果model和你给的参数的model并没有直接关联,直接使用cake的find函数应该是免不了中间的一步查询的。
daxiongshishen 2010-12-30
  • 打赏
  • 举报
回复
因为这样 老是感觉自己级联没学好似的。。
daxiongshishen 2010-12-30
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 ihefe 的回复:]

SQL code

select * from cities a
join airports b on a.id=b. city_id
join airports c on a.id=b. city_id
join flights d on b.id=d.from_airport_id and c.id=d. to_airport_id
where b. airport_name ="从机场……
[/Quote]

直接用sql啊 有没有用find()方法 设置级联一次性查出来呢。。
ihefe 2010-12-30
  • 打赏
  • 举报
回复

select * from cities a
join airports b on a.id=b. city_id
join airports c on a.id=b. city_id
join flights d on b.id=d.from_airport_id and c.id=d. to_airport_id
where b. airport_name ="从机场名" and c.airport_name="至机场名"

--看看行不行。
ihefe 2010-12-30
  • 打赏
  • 举报
回复
噢看错。。

ihefe 2010-12-30
  • 打赏
  • 举报
回复
少个机场表?
daxiongshishen 2010-12-30
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ihefe 的回复:]

from_airport_id(出发机场) 是名字还是id
[/Quote]
厄 是id 那个to_airport_id 也是id
ihefe 2010-12-30
  • 打赏
  • 举报
回复
from_airport_id(出发机场) 是名字还是id
daxiongshishen 2010-12-30
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 life169 的回复:]

把你三个表的各个字段都贴出来,把字段的相关说明也贴出来,我们才好给你个完整的查询代码
[/Quote]

1:cities表
id city_name(城市名)

2:airports表
id airport_name(机场名) city_id(城市id)

3:flights表
id flight_name(航班名) from_airport_id(出发机场) to_airport_id(目的机场)
另外 3个表的级联关系已经设好了
life169 2010-12-30
  • 打赏
  • 举报
回复
把你三个表的各个字段都贴出来,把字段的相关说明也贴出来,我们才好给你个完整的查询代码

4,250

社区成员

发帖
与我相关
我的任务
社区描述
国内外优秀PHP框架讨论学习
社区管理员
  • Framework
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧