Cakephp:HasOne 关系
我正在尝试建模以下内容:
旅程有一个 id、一个 fromCity 和一个 toCity。
我的数据库如下所示:
表旅程:
id | fromCity | toCity
1 2 4
2 4 2
来自城市的表:
id | name
2 paris
4 london
我为城市和旅程定义了模型。
在我的旅程模型文件中,我想声明一个 $hasOne 归档,以便将 fromCity id 解析为城市名称。
我尝试遵循 hasOne 上的 CakePHP 教程 (http://book.cakephp.org/view/80 /hasOne),但我无法理解如何解析两个外键。
有人可以向我解释一下 var $hasone = ...
必须如何查找这种情况吗?
编辑:模型:
<?php class City extends AppModel { var $name='City';} ?>
<?php class Journey extends AppModel { var $name='Journey'; /*var $hasOne=array(...)*/} ?>
编辑2:
var $hasOne = array(
'CityFrom' => array(
'className' => 'City',
'conditions' => 'Journey.fromAirport = CityFrom.id',
'dependent' => true,
'foreignKey' => 'id = Journey.fromCity' ),
'CityTo' => array (
'className' => 'City',
'conditions' => 'Journey.toCity = CityTo.id',
'dependent' => true,
'foreignKey' => 'id = Journey.toCity'
)
);
似乎适用于旅程表的第一个条目。所有其他值均为空。我认为问题是由于此查询中有两列具有相同名称而引起的。
I'm trying to model the following:
A journey has an id, a fromCity and a toCity.
My DB looks like this:
Table journey:
id | fromCity | toCity
1 2 4
2 4 2
Table fromCity:
id | name
2 paris
4 london
I have models defined for the city and for the journey.
In my model file for the journey I want to declare a $hasOne filed in order resolve the fromCity id to the city's name.
I tried to follow the CakePHP tutorial on hasOne (http://book.cakephp.org/view/80/hasOne) but I can't wrap my head around how to resolve two foreign keys.
Can someone please explain to me how a var $hasone = ...
has to look for this case?
Edit: The models:
<?php class City extends AppModel { var $name='City';} ?>
<?php class Journey extends AppModel { var $name='Journey'; /*var $hasOne=array(...)*/} ?>
Edit 2:
var $hasOne = array(
'CityFrom' => array(
'className' => 'City',
'conditions' => 'Journey.fromAirport = CityFrom.id',
'dependent' => true,
'foreignKey' => 'id = Journey.fromCity' ),
'CityTo' => array (
'className' => 'City',
'conditions' => 'Journey.toCity = CityTo.id',
'dependent' => true,
'foreignKey' => 'id = Journey.toCity'
)
);
Seems to work for the first entry of the journey table. All other's values are null. I think the problem occours from having two columns with the same name in this query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Rin 提到的,您需要使用
beLongsTo
而不是hasOne
。这是一个关于 与同一模型的多个关系 来自 Cookbook。希望有帮助。As Rin mentioned,you need to use
beLongsTo
instead ofhasOne
.Here's a example about Multiple relations to the same model from Cookbook.Hope it helps.首先,您的链接指向
1.2
文档,您可能下载了1.3
。在
1.3
中,您可能还应该在FromCity
和ToCity
模型上使用belongsTo
(但我可能是错的,长不久前我用过它:)First of all your link leads to
1.2
docs, you probably downloaded1.3
.In
1.3
, you should probably also usebelongsTo
onFromCity
andToCity
Models (but I could be wrong, long time ago I used it :)