duanjing7298 2011-12-15 19:30
浏览 38
已采纳

CakePHP - MVC模型关联 - 如何构建此数据模型?

quick question that I have been stuck with since hours:

For my cakePHP website project (using version 2.0) I have 2 Models. They are a bit obscure so I'll translate the model to the standard blog post models.

So I have a "Posts" model and for those many "Categories".

class Post
$belongsTo = 'Category'

class Category
$hasMany = 'Post'

So far so good. Now I want every category to have exactly one (mandatory) 'main post'.

How would I associate that?

  • Another 'MainPost' Model? That seems redundant as it would have the same content as the posts.
  • A boolean 'is_main' column in the posts? Doesn't seem right since only one post of each category is allowed to be "main".
  • A 'mainpost_id' column in the categories? Sounds good but "$belongsTo" is the only association that allows the foreign key to be in the current class. And to say that a Category belongsTo Post when the opposite is also true seems wrong to me. Also belongsTo is a many-to-one association and what I want is kind of a one-to-one association.

Please help me, [insert name]. You're my only hope. ;)

Edit: I guess it would be great if there was a way to have a "hasOne" relationship but have the foreign key in the same class that $hasOne X and not in the other as is standard.

  • 写回答

2条回答 默认 最新

  • doujiao2014 2011-12-16 21:39
    关注

    Here is one solution:

    [ categories ]
    id
    name
    mainpost_id
    
    [ posts ]
    id
    category_id
    title
    text
    
    • Category hasMany Post
    • Post belongsTo Category
    • Category hasOne MainPost (see code)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题