Cakephp:模型中的多个属性

问题描述:

In a model, is it possible to do multiple iterations of belongsTo?

Assuming 3 tables, alerts, schedules, tasks and the model is for alerts. I want to get at a field from tasks but I have to join through schedules.

 alerts.schedule_id -> schedules.tasks_id -> tasks.name

I tried this syntax:

var $belongsTo = array( 
         'Schedule' => array( 
             'className' => 'Schedule', 
             'foreignKey' => 'schedule_id' 
         ), 
         'Task' => array( 
             'className' => 'Task', 
             'foreignKey' => 'task_id' 
         ));

But that just joins both Schedules and Tasks directly to Alerts (here's the sql that was generated:

LEFT JOIN `schedules` AS `Schedule` ON (`Alert`.`schedule_id` = `Schedule`.`id`) LEFT JOIN `tasks` AS `Task` ON (`Alert`.`task_id` = `Task`.`id`)
)

在模型中,是否可以对belongsTo进行多次迭代? p>

假设3个表,警报,日程表,任务和模型用于警报。 我想从任务中获取一个字段,但我必须通过日程安排加入。 p>

  alerts.schedule_id  - >  schedules.tasks_id  - >  tasks.name 
  code>  pre> 
 
 

我尝试了这种语法: p>

  var $ belongsTo = array(
'Schedule'  =>数组(
'className'=>'计划',
'foreignKey'=>'schedule_id'
),
'任务'=>数组(
'className'=>  '任务',
'foreignKey'=>'task_id'
)); 
  code>  pre> 
 
 

但这只是将计划和任务直接连接到警报(这里是 生成的sql: p>

  LEFT JOIN`cheleles`AS`Andline`ON(`Alert` .schedule_id` =`Schedule``id`)LEFT JOIN` 任务`AS`任务`ON(`Alert``task_id` =`Task` .id`)
)
  code>  pre> 
  div>

I ended up setting this property:

$this->Alert->recursive = 2;

In the index() function of the alerts controller.

Then I didn't have to do a separate find and was able to reference the name field in the Tasks table in index.ctp like this:

<td><?php echo $alert['Schedule']['Task']['name']; ?>&nbsp;</td>

Try this.

in alert.php

CLass Alert extends AppModel{
    var $name = 'Alert';
    var $belongsTo = array( 
         'Schedule' => array( 
             'className' => 'Schedule', 
             'foreignKey' => 'schedule_id' 
         )
    ); 
}

in schedule.php

 CLass Schedule extends AppModel{
        var $name = 'Schedule';
        var $belongsTo = array( 
             'Task' => array( 
                'className' => 'Task', 
                'foreignKey' => 'task_id' 
            )
        ); 
    }

then find with recursive=>2