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.

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

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错