how to configure routes for child controllers in CakePHP 3.x?

别等时光非礼了梦想. 提交于 2020-01-03 03:08:07

问题


  1. Reports has many ReportInstances
  2. ReportInstances belongs to Reports

I would like to have the url /reports/:report-id/instances to point to the action index_by_report_id inside ReportInstancesController.php

How do I configure the routes.php accordingly?

UPDATE:

I tried nested resources as described here: http://book.cakephp.org/3.0/en/development/routing.html#creating-nested-resource-routes

Here are my routes

$routes->resources('Reports', [
    'map' => [
        'standard' => [
            'action' => 'standard',
            'method' => 'GET',
        ]
    ]
]);

$routes->resources('Reports', function ($routes) {
    $routes->resources('ReportInstances');
});

When I do a /reports/1/instances, it goes to ReportsController looking for action 1.

Please advise.


回答1:


Do this in your routes.php

$routes->resources('Parents', function ($routes) {
    $routes->resources('Children');
});

$routes->resources('Children');

In ChildrenController.php,

protected function _prepareConditions() {
    $parentId = isset($this->request->params['parent_id']) ? $this->request->params['parent_id'] : null;

    if ($parentId == null) {
        return [];
    }

    return [
        'Children.parent_id' => $parentId
    ];
}

public function index()
{
    $conditions = $this->_prepareConditions();

    $this->paginate = [
        'contain' => ['Parents'],
        'conditions' => $conditions
    ];
  // ... and so on

You will be able to do the following:

  1. /parents/1/children
  2. /parents/1/children.json
  3. /children
  4. /children.json

Why this works?

http://book.cakephp.org/3.0/en/development/routing.html#creating-nested-resource-routes

tells us that basically to basically retrieve the parent id from the request params.

What it does not say explicitly is that, the routes will then reuse the basic 5 functions: index, add, view, delete, edit even when you nest them under a parent url.

Why do you still have a separate resources route for the Children?

This allows the /children and /children.json to work if you need them as well.

What about add?

I haven't tried that but I do not foresee any issues with using that as

  1. /parents/1/children/add
  2. /parents/1/children/add.json
  3. /children/add
  4. /children/add.json


来源:https://stackoverflow.com/questions/32032572/how-to-configure-routes-for-child-controllers-in-cakephp-3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!