how to configure routes for child controllers in C

2019-06-06 18:53发布

问题:

  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