CakePHP 与非传统数据库的关联
我们正在转换一个应用程序以与 CakePHP 2.0.3 一起使用。 由于某种原因,我似乎无法在模型之间建立适当的关系。
下面是一个示例:
- 用户 (id, petid, 国家/地区, picid, ...)
- 宠物 (id, userid, picid, ...)
- 图片 (id, albumid, ....)
- 相册 (id, userid, petid, . ..)
它们的含义如下: - 一个用户可以拥有多只宠物,但同时只能选择一只宠物(因此,用户中的petid)
- 宠物属于一个用户
- 宠物和用户可以有多张照片,但只能有一张个人资料照片,因此 Pet.picid 和 User.picid
- 宠物和用户可以拥有多个相册
我在 CakePHP 中设置了我的模型,但我无法弄清楚在它们之间使用哪些关系,因为数据库不遵循约定。 我已尝试以下操作:
用户
->有很多(宠物)
-> hasOne(图片)
-> hasMany(相册)宠物
-> belongsTo(User)(工作正常,带有外键用户ID)
-> hasMany(专辑)
-> hasOne(图片)相册
-> hasMany(图片)
---- 实现这一目标的逻辑?它要么属于用户,要么属于宠物-----
->属于(用户)
->属于(宠物)
- 图片
-> belongsTo(Album)
我是 CakePHP 的新手,不知道如何去这里。 您有什么建议吗?
We are converting an application for use with CakePHP 2.0.3.
For some reason, I cannot seem to set proper relations between my models.
Here's an example:
- User (id, petid, country, picid, ...)
- Pet (id, userid, picid, ...)
- Picture (id, albumid, ....)
- Album (id, userid, petid, ...)
The meanings of these are the following:
- A user can have multiple pets, but can only have selected one pet at the same time (therefore, petid in User)
- Pets belong to one user
- Pets and Users can have multiple pictures, but only one profile picture, therefore Pet.picid and User.picid
- Pets and users can have multiple Albums
I set up my models in CakePHP, but I cannot figure out which relations to use between them since the Database is not following the conventions.
I've tried the following:
User
-> hasMany(Pets)
-> hasOne(Picture)
-> hasMany(Album)Pet
-> belongsTo(User) (works fine, with foreignkey userid)
-> hasMany(Album)
-> hasOne(Picture)Album
-> hasMany(Picture)
---- Logic to achieve this? It either belongs to a user or pet-----
-> belongsTo(User)
-> belongsTo(Pet)
- Picture
-> belongsTo(Album)
I'm new to CakePHP and cannot figure out the way to go here.
Do you have any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议在您的关系中使用 别名将帮助您了解返回的数据。
例如,您的 User 模型可以在其关联中使用 SelectedPet 和 ProfilePicture:
User.php 模型
您的 Pet 模型也可以使用ProfilePicture:
图片模型:
..最后是你的相册模型:
关于相册<的逻辑/strong> 属于一个用户或宠物,您可以在保存数据或返回数据时在控制器中处理它。即用户优先于宠物。
我希望这有帮助。
I would suggest using Aliases in your relationships which will help get your head around the data being returned.
For example, your User model could use SelectedPet and ProfilePicture in it's associations:
User.php model
Your Pet model could use ProfilePicture as well:
Picture model:
..and finally your Album model:
With regards to the logic of an Album belonging to a User or a Pet, you could just handle this in your controller when saving data or returning it. I.e User is given preference over Pet.
I hope this helps.