cakephp从不同的模型获取数据

时间:2011-10-09 11:04:21

标签: cakephp

我是cakephp的新手,我在构建应用程序时遇到了问题。在我的应用程序中,我有称为Customer,Job,Jobtask,Jobtasksvehicle和Vehicle的模型。他们的数据库关系是Customer-> Job-> Jobtask-> Jobtasksvehicle-> Vehicle。 我有一个名为工作表的页面,在该表中我将显示客户名称,工作ID,工作任务和车辆名称。我可以获得客户名称,工作ID和工作任务显示,但我无法弄清楚如何在那里显示车辆名称。任何人都可以帮助我。

这是页面的模型

    function sch($id = null) {
    if (!$id) {
        $this->Session->setFlash(__('Invalid job', true));
        $this->redirect(array('action' => 'index'));
    }
    $this->set('job', $this->Job->read(null, $id));

我想在此表中显示车辆名称

<div class="related">

<?php
    $i = 0;
    foreach ($job['Jobtask'] as $jobtask):
        $class = null;
        if ($i++ % 2 == 0) {
            $class = ' class="altrow"';
        }
    ?>
    <tr<?php echo $class;?>>
        <td><?php echo $jobtask['id'];?></td>
        <td><?php echo $jobtask['job_id'];?></td>
        <td><?php echo $jobtask['rate_id'];?></td>
        <td><?php echo $jobtask['type'];?></td>
        <td><?php echo $jobtask['date'];?></td>
        <td><?php echo $jobtask['starttime'];?></td>
        <td><?php echo $jobtask['timeband'];?></td>
        <td><?php echo $jobtask['settlement'];?></td>       
        <td><?php echo $job['Jobtasksvehicle']['vehicle_id'];?></td>    

        <td class="actions">



            <?php echo $this->Html->link(__('Allocate Vehicle', true), array('controller' => 'jobtasksvehicles','action' => 'add', $jobtask['id'])); ?>
            <?php echo $this->Html->link(__('View', true), array('controller' => 'jobtasks', 'action' => 'view', $jobtask['id'])); ?>
            <?php echo $this->Html->link(__('Edit', true), array('controller' => 'jobtasks', 'action' => 'edit', $jobtask['id'])); ?>
            <?php echo $this->Html->link(__('Delete', true), array('controller' => 'jobtasks', 'action' => 'delete', $jobtask['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $jobtask['id'])); ?>
        </td>
    </tr>
<?php endforeach; ?>
</table>

这是模型之间的关系

客户有很多工作

作业属于客户

Job hasMany Jobtask

Jobtask belongsTo Job

Jobtask有很多Jobtasksvehicle

Jobtasksvehicle属于Jobtask and Vehicle

车辆有多个Jobtasksvehicle

1 个答案:

答案 0 :(得分:0)

使用Ross包含的Containable行为是最好的方法。添加到您的工作模型:

var $actsAs = array('Containable');

在你的控制器中:

$job = $this->Job->find('first', array(
    'conditions' => array('Job.id' => $id),
    'contain' => array(
        'Jobtask' => array(
            'Jobtasksvehicle' => array(
                'Vehicle'
             ),
         ),
    ),
));
$this->set(compact('job'));

有关更多帮助,请参阅Containable documentation。我将把视图中的数据争论留给你。