Как получить общую стоимость из оценки, чтобы показать в index.ctp, используя CakePHP - PullRequest
0 голосов
/ 21 июля 2011

У меня есть оценки hasMany EstimateDetails hasMany Items.То, что я пытаюсь сделать, это получить итоговую оценку по моим оценкам. Представление индекса.

Отладка $ оценок на index.ctp:

Array
(
[0] => Array
    (
        [Estimate] => Array
            (
                [id] => 1
                [name] => City Base Cinema 10
                [employee_id] => 1
                [created] => 2011-07-12 18:08:37
                [modified] => 2011-07-12 18:08:37
            )

        [Employee] => Array
            (
                [id] => 1
                [first_name] => Edward
                [last_name] => Ramon
                [phone] => 2106959672
                [hourly_pay] => 0.00
                [position_id] => 2
                [created] => 2011-07-12 17:56:42
                [modified] => 2011-07-12 17:56:42
                [fullname] => Edward Ramon
                [Position] => Array
                    (
                        [id] => 2
                        [name] => Estimator
                    )

                [Estimate] => Array
                    (
                        [0] => Array
                            (
                                [id] => 1
                                [name] => City Base Cinema 10
                                [employee_id] => 1
                                [created] => 2011-07-12 18:08:37
                                [modified] => 2011-07-12 18:08:37
                            )

                    )

                [Job] => Array
                    (
                    )

            )

        [EstimateDetail] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [estimate_id] => 1
                        [qty] => 10
                        [item_id] => 1
                        [feet] => 10
                        [inches] => 2
                        [adjustment] => -0.20
                        [Estimate] => Array
                            (
                                [id] => 1
                                [name] => City Base Cinema 10
                                [employee_id] => 1
                                [created] => 2011-07-12 18:08:37
                                [modified] => 2011-07-12 18:08:37
                            )

                        [Item] => Array
                            (
                                [id] => 1
                                [type] => W
                                [eje] => W
                                [description] => 44x335
                                [price unit] => perpound
                                [weight] => 335
                                [price] => 0.80
                                [fulldesc] => W44x335
                            )

                    )

                [1] => Array
                    (
                        [id] => 3
                        [estimate_id] => 1
                        [qty] => 3
                        [item_id] => 1
                        [feet] => 4
                        [inches] => 5
                        [adjustment] => 0.00
                        [Estimate] => Array
                            (
                                [id] => 1
                                [name] => City Base Cinema 10
                                [employee_id] => 1
                                [created] => 2011-07-12 18:08:37
                                [modified] => 2011-07-12 18:08:37
                            )

                        [Item] => Array
                            (
                                [id] => 1
                                [type] => W
                                [eje] => W
                                [description] => 44x335
                                [price unit] => perpound
                                [weight] => 335
                                [price] => 0.80
                                [fulldesc] => W44x335
                            )

                    )

                [2] => Array
                    (
                        [id] => 4
                        [estimate_id] => 1
                        [qty] => 10
                        [item_id] => 1
                        [feet] => 10
                        [inches] => 10
                        [adjustment] => 0.00
                        [Estimate] => Array
                            (
                                [id] => 1
                                [name] => City Base Cinema 10
                                [employee_id] => 1
                                [created] => 2011-07-12 18:08:37
                                [modified] => 2011-07-12 18:08:37
                            )

                        [Item] => Array
                            (
                                [id] => 1
                                [type] => W
                                [eje] => W
                                [description] => 44x335
                                [price unit] => perpound
                                [weight] => 335
                                [price] => 0.80
                                [fulldesc] => W44x335
                            )

                    )

                [3] => Array
                    (
                        [id] => 5
                        [estimate_id] => 1
                        [qty] => 10
                        [item_id] => 3
                        [feet] => 10
                        [inches] => 10
                        [adjustment] => 0.00
                        [Estimate] => Array
                            (
                                [id] => 1
                                [name] => City Base Cinema 10
                                [employee_id] => 1
                                [created] => 2011-07-12 18:08:37
                                [modified] => 2011-07-12 18:08:37
                            )

                        [Item] => Array
                            (
                                [id] => 3
                                [type] => W
                                [eje] => W
                                [description] => 44x290
                                [price unit] => perpound
                                [weight] => 290
                                [price] => 0.80
                                [fulldesc] => W44x290
                            )

                    )

                [4] => Array
                    (
                        [id] => 6
                        [estimate_id] => 1
                        [qty] => 10
                        [item_id] => 6
                        [feet] => 10
                        [inches] => 2
                        [adjustment] => 0.00
                        [Estimate] => Array
                            (
                                [id] => 1
                                [name] => City Base Cinema 10
                                [employee_id] => 1
                                [created] => 2011-07-12 18:08:37
                                [modified] => 2011-07-12 18:08:37
                            )

                        [Item] => Array
                            (
                                [id] => 6
                                [type] => PL
                                [eje] => PL
                                [description] => 4X3
                                [price unit] => ea
                                [weight] => 1
                                [price] => 0.30
                                [fulldesc] => PL4X3
                            )

                    )

            )

        [Job] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [job_number] => 2353
                        [name] => City Base Cinema 10
                        [company_id] => 1
                        [estimate_id] => 1
                        [contract_amount] => 253000
                        [employee_id] => 2
                        [location_id] => 1
                        [created] => 2011-07-12 18:17:59
                        [modified] => 2011-07-16 12:17:55
                        [Company] => Array
                            (
                                [id] => 1
                                [name] => Search Construction
                                [address] => 123 street
                                [city] => San Antonio
                                [state] => TX
                                [zip] => 78023
                                [company_type_id] => 1
                                [created] => 2011-07-12 18:16:37
                                [modified] => 2011-07-12 18:16:37
                            )

                        [Estimate] => Array
                            (
                                [id] => 1
                                [name] => City Base Cinema 10
                                [employee_id] => 1
                                [created] => 2011-07-12 18:08:37
                                [modified] => 2011-07-12 18:08:37
                            )

                        [Employee] => Array
                            (
                                [id] => 2
                                [first_name] => Adam
                                [last_name] => Morales
                                [phone] => 
                                [hourly_pay] => 20.00
                                [position_id] => 1
                                [created] => 2011-07-16 12:16:49
                                [modified] => 2011-07-16 12:16:49
                                [fullname] => Adam Morales
                            )

                        [Location] => Array
                            (
                                [id] => 1
                                [address] => 456 street
                                [city] => Helotes
                                [state] => TX
                                [zip] => 78023
                                [location_type_id] => 1
                                [full_local] => 456 street Helotes, TX 78023
                            )

                    )

            )

    )

)

Я попытался установить переменную Field на оценкеМодель:

var $virtualFields = array('total' => 'SUM(EstimateDetail.qty*EstimateDetail.Item.weight*EstimateDetail.Item.price)');

Мой Index.ctp:

<tr>
        <th><?php echo $this->Paginator->sort('id');?></th>
        <th><?php echo $this->Paginator->sort('name');?></th>
        <th><?php echo $this->Paginator->sort('employee');?></th>
        <th><?php echo $this->Paginator->sort('created');?></th>
        <th><?php echo $this->Paginator->sort('modified');?></th>
        <th class="actions"><?php __('Actions');?></th>
</tr>
<?php
$i = 0;
foreach ($estimates as $estimate):
    $class = null;
    if ($i++ % 2 == 0) {
        $class = ' class="altrow"';
    }
?>
<tr<?php echo $class;?>>
    <td><?php echo $estimate['Estimate']['id']; ?>&nbsp;</td>
    <td><?php echo $estimate['Estimate']['name']; ?>&nbsp;</td>
    <td>
        <?php echo $this->Html->link($estimate['Employee']['fullname'], array('controller' => 'employees', 'action' => 'view', $estimate['Employee']['id'])); ?>
    </td>
    <td><?php echo $estimate['Estimate']['created']; ?>&nbsp;</td>

    <td class="actions">
        <?php echo $this->Html->link(__('View', true), array('action' => 'view', $estimate['Estimate']['id'])); ?>
        <?php echo $this->Html->link(__('Edit', true), array('action' => 'edit', $estimate['Estimate']['id'])); ?>
        <?php echo $this->Html->link(__('Delete', true), array('action' => 'delete', $estimate['Estimate']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $estimate['Estimate']['id'])); ?>
    </td>
</tr>

, и я получаю сообщение об ошибке.

Полученная ошибка:

Warning (2): Invalid argument supplied for foreach() [APP/views/estimates/index.ctp, line 15]

и Sql:

1054: Unknown column 'EstimateDetail.qty' in 'field list

Пожалуйста, помогите.

1 Ответ

0 голосов
/ 22 июля 2011

Короткий ответ будет: не пытайтесь делать то, что вы делаете с SQL / virtualFields (если вы хотите, я могу подробно объяснить, почему).

Просто переберите свои результаты с помощью foreach($estimates) и вычислите сумму самостоятельно в PHP.

ОБНОВЛЕНИЕ : Вы не можете (легко) использовать агрегат (SUM) в find() в вашем примере, потому что:

  1. для этого поиск должен быть выполнен в одном запросе - т.е. с использованием JOIN s - и Cake не будет охотно использовать JOIN s для отношений hasMany (вместо этого он выполняет много простых SELECT s), что означает, что вы пришлось бы делать их вручную (http://book.cakephp.org/view/1047/Joining-tables).
  2. запрос с SUM вернул бы только одну строку (сгруппированную), что означает, что вам нужно будет выполнить нетривиальный подзапрос, чтобы получить и SUM И ваши результаты.
...