【问题标题】:Multiple relations to same table from different models来自不同模型的同一张表的多个关系
【发布时间】:2014-03-25 16:21:42
【问题描述】:

我想要一种简单且可重用的方法来与具有不同模型的特定表共享关系。我想要做的是指定一个表的可能性,该表具有一个外键列,例如“parent_id”,然后将此表/模型与我的应用程序中的多个模型相关联。有没有办法在蛋糕中做到这一点,这是最好的方法?我想我需要在此表中添加一个列,以指定每行链接到哪个表,例如:

表1

id 0 1 2 名称 名称0 名称1 名称2 ...

表2

id 0 1 2 名称 名称0 名称1 名称2 ...

Common_table:

id 0 1 ... parent_id 0 0 parent_table Table1 Table2

我希望上面的解释有意义,提前谢谢!

【问题讨论】:

    标签: php database cakephp


    【解决方案1】:

    是的

    当你建立关系时,你也可以设置条件

    一个示例可能是一个应用程序,其中您有许多可以评论的模型,因此它们都与Comment Model 存在 hasMany 关系。

    您可以在 cmets 表中创建一个列来存储被评论模型的名称和一个 parent_id 列来存储 ID。

    所以 cmets 表通常类似于

    id | parent_id | model_name | comment_text         | user_id
    ---+-----------+------------+----------------------+-------
    1  | 15        | Post       | I like this Post     | 3
    1  | 15        | Post       | I like this Post too | 5
    2  | 19        | Receipt    | This receipt is good | 3
    

    在您的 Post 模型中您可以这样做

    public hasMany =array(
        'Comment' => array(
            'foreignKey' => 'parent_id',
            'conditions' => array('Comment.model_name' => 'Post')
        )
    

    在您的Receipt 模型中您可以这样做

    public hasMany =array(
        'Comment' => array(
            'foreignKey' => 'parent_id',
            'conditions' => array('Comment.model_name' => 'Receipt')
        )
    

    等等

    【讨论】:

    • 似乎很有希望...有没有办法自动化诸如获取链接父级的所有 cmets、保存等内容?我想我应该使用 Behavior?
    • 是的,一种行为可能是正确的选择。但是使用上面的代码,当您执行 $this->Post->find('first', ...) 之类的操作时,您会收到一个包含他所有 cmets 的帖子
    • 任何关于如何在行为中做到这一点的提示?
    • @cpl 你的问题有点笼统......你到底想达到什么目标?
    猜你喜欢
    • 2020-10-27
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 2013-02-17
    • 2013-05-14
    相关资源
    最近更新 更多