dongtuliao6760 2014-03-25 07:58
浏览 7
已采纳

来自不同模型的同一表的多个关系

I would like to have a simple and reusable way of sharing a relations with a specific table with different models. What I would like to do is the possibility to specify a table, with a foreign key column such as "parent_id" and then associate this table/model to several models in my app. Is there a way to do this in cake, and which is the best way? I guess I would need an additional column in this table, to specify which is the table every row is linked to, e.g.:

Table1

id 0 1 2 name name0 name1 name2 ...

Table2

id 0 1 2 name name0 name1 name2 ...

Common_table:

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

I hope the explanation above made sense, thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongyan6235 2014-03-25 08:21
    关注

    yes

    when you create a relationship you can also set the conditions

    An example could be an application in which you have many models that can be commented, so they all are in a hasMany relationship with Comment Model.

    You can create a column in comments table storing the name of the model being commented and a parent_id column storing the id.

    So the comments table would tipically be something like

    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
    

    in your Post Model you can do

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

    in your Receipt Model you can do

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

    and so on

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3