简体   繁体   中英

CAKEPHP Stucked in Associating Models

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. :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM