doutangtan6386 2011-11-13 06:01
浏览 26
已采纳

CAKEPHP陷入了关联模式

Im using cakephp and Im stuck about the idea of listing multiple models, here's my scenario:

I have two major models namely Task and Events. I used the Events model to track all changes. this has the ff fields: id, model, model_id, changed I used Events table to track multiple model changes. so when something changed to Task model it will be logged to Events models (get the idea??)

What I want to do is whenever i used the find method for Event model, i want to list the model information (for example, the Task model) together with my Events information like this:

array(
    [0] => array (
        [Event] => array(
            id => 1
            model => Task
            model_id => 2
            changed => array()
        )

        [Task] => array(
            id => 2
            name => Task 1
            descp => Test Task
        )

    )
)

Note: The model can be any model, it can be Projects model.

At my task.php, it is no problem because i can easily declare:

var $hasMany = array(
    'Events' => array(
            'className' => 'Events',
            'foreignKey' => 'model_id',
            'dependent' => false,
            'conditions' => array('Events.model' => 'Task')
        )
    );

I can get Events information using the find method on task although using

 $this->Task->Event->find('all'); 

will not work, i dont know why.

So as soon as I declare, something like this in my Event Model:

var $belongsTo = array(
    'Task' => array(
        'className' => 'Task',
        'foreignKey' => 'model_id',
        'conditions' => array('Event.model' => 'Task', 'Event.model_id' => 'Task.id'),
        'fields' => '',
        'order' => ''
    )
);

will throw an SQL error. Do you guys have an idea how to implement it?? Thanks in advanced. :)

  • 写回答

1条回答 默认 最新

  • dongzi0602 2011-11-13 11:29
    关注

    I use polymorphic models all the time. The reason that $this->Task->Event->find('all') doesn't work is that you were performing the find on the Event model which, until you defined its belongsTo association, didn't have any means of retrieving the Task info.

    As for now, the only thing I see that looks odd is that you've aliased your Task association as Events (plural) rather than its singular version which is the convention for models. You also identified the className as the plural version.

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

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题