【问题标题】:Retrieving data from different models从不同模型中检索数据
【发布时间】:2011-10-14 04:27:38
【问题描述】:

我一直在尝试在同一页面中显示来自不同模型的数据,但仍然无法正常工作。 这是模型之间的关系

客户有很多工作

工作属于客户

Job hasMany Jobtask

Jobtask 属于Job

Jobtask 有许多 Jobtasksvehicle

Jobtasksvehicle 属于 Jobtask 和 Vehicle

Vehicle hasMany Jobtasksvehicle

这是我的工作主管

    function sch($id = null) {
    if (!$id) {
        $this->Session->setFlash(__('Invalid job', true));
        $this->redirect(array('action' => 'index'));
    }
    $job = $this->Job->find('first', array(
'conditions' => array('Job.id' => $id),
'contain' => array('Customer',
    'Jobtask' => array(
        'Jobtasksvehicle' => array(
            'Vehicle'
         ),
     ),
),

));

我要做的是显示来自 Customer、Job、Jobtask、Jobtasksvehicle、Vehicle 模型的数据。 我可以从 Customer、Job 和 Jobtask 获取数据显示,但不能从 Jobtasksvehicle 和 Vehicle 模型获取数据显示。我想显示分配给每个作业任务的每辆车(车辆模型)。

这是我想在同一个表中显示作业任务和车辆模型的地方。

    <?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['Vehicle']['vehiclemodel'];?></td>
    </tr>
<?php endforeach; ?>
</table>

?>

【问题讨论】:

  • 查找功能似乎是正确的。您是否尝试调试 $job 变量?您查看的记录是否可能没有关联 Jobtasksvehicle AND Vehicle?

标签: cakephp model


【解决方案1】:

一切似乎都很好,你需要把find放在recursive = 3中,像这样

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

但可包含的行为仍应自动计算递归,请确保您正在加载可包含的行为。

查看有关containable behaviour的书

还要检查是否正在执行 sql 查询,如果出现 sql 查询,您可能需要指定字段(您可能需要使用 Job.* o Vehicle.* 来获取所有字段...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-10
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    相关资源
    最近更新 更多