CakePHP:使用条件参数检索列表

我很难理解如何使用条件格式检索关联数据。我正在使用 CakePHP 3.7.9。


餐桌产品

id

name

customer_code

表订单

id

name

date

表 item_orders

id

order_id

name

product_id

description

在(另一个控制器的)视图中,我有两个select控件。第一个填充id|name了现有订单。当用户选择一个时,select应按照以下条件填充第二个控件:

  • 如果product_id不为空 ->name (customer_code)products表中检索

  • 否则使用该description

ajax用来将电流发送order_id到控制器,该控制器应该发回填充第二个所需的 html select

<?php $this->Html->scriptStart(['block' => 'script', 'inline' => false]); ?>

    $(document).on('change', '#order-id', function() {

        $.ajax({

            type: "POST",

            headers: { 'X-CSRF-Token': <?= json_encode($this->request->getParam('_csrfToken')); ?> },

            url:  '<?php echo Router::url(array('controller' => 'ItemDeliveryNotes', 'action' => 'getOrderItems'));?>',

            data: { 'orderId': $('#order-id').val() },

            success: function(response) {

                $('#itemOrders').html(response.data.itemOrders);

            }

        });

    });

<?php $this->Html->scriptEnd(); ?>


public function getOrderItems()

{

    if ($this->request->is(['ajax', 'post']))

    {

        $id = $this->request->getData('orderId'); // <-- fixed

        $items = $this->getItems($id);

        $combo = [];

        foreach ($items as $key => $value)

        {

            $combo[] = "<option value='" . $key . "'>" . $value . "</option>";

        }


        $data = ['data' => ['itemOrders' => $combo]];

        return $this->json($data);

    }

}


private function getItems($id = null)

{

    $items = ???; // <-- here I need to retrieve the list as above

    return $items;

}

我能够从单一来源获取数据,但在这种情况下,我不明白如何编写查询。


SMILET
浏览 149回答 1
1回答

莫回无

如评论中所述,您将数据发送为orderId,但访问它为order_id,并且您认为您还使用了错误的控制器名称。您很可能在生成 URL 时没有收到错误,因为您正在使用fallbacks或手动捕获所有路由,即类似 的路由/:controller/:action,它将匹配任何控制器/操作。向不存在的端点发出请求时将引发错误,但您尚未为 AJAX 调用定义错误/失败处理程序,因此错误正在被吞没,您的 CakePHP 错误中仍然应该有一些东西日志。话虽如此,您真的不应该在每行发出额外的查询(即在valueField回调中发出查询),而是在 SQL 级别进行过滤,例如使用CASE表达式,或包含Products关联,以便您拥有所需的所有数据用于在 PHP 级别进行过滤,应该很简单:$items = $this->ItemsDeliveryNotes->Orders->ItemOrders&nbsp; &nbsp; ->find('list', [&nbsp; &nbsp; &nbsp; &nbsp; 'keyField' => 'id',&nbsp; &nbsp; &nbsp; &nbsp; 'valueField' => function (\Cake\Datasource\EntityInterface $row) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($row->has('product')) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $row->product->name . ' (' . $row->product->customer_code . ')';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $row->description;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ])&nbsp; &nbsp; ->contain('Products')&nbsp; &nbsp; ->where([&nbsp; &nbsp; &nbsp; &nbsp; 'order_id' => $id&nbsp; &nbsp; ]);
打开App,查看更多内容
随时随地看视频慕课网APP