CakePHP 2.x Accessing Another Model

84 Views Asked by At

Noob to cakePHP here.

Bicycle belongsTo Stand
Stand hasMany Bicycle
Stand belongsTo Station
Station hasMany Stand

I've baked the CRUDs and now I want to display the station name when I view a bicycle. How should I define the bicycle - station relationship? Or what do I need to do to include the station model in the bicycles controller?

What I've tried so far. Which throws a "Notice (8): Undefined index: Station": BicyclesController.php:

public function index() {
        $this->Bicycle->recursive = 2;
        $this->set('bicycles', $this->Paginator->paginate());
    }

index.ctp:

    <?php echo $this->Html->link($bicycle['Station']['name'].$bicycle['Stand']['stand_no'], array('controller' => 'stands', 'action' => 'view', $bicycle['Stand']['id'])); ?>

Help!

1

There are 1 best solutions below

0
On BEST ANSWER

Since you have no direct relationship from Bicycle to Station, its not going to be available within $bicycle['Station'] Its more likely to be available in $bicycle['Stand']['Station]['name'].

In order to see if its actually being returned with recursive set as it is, I would run the query again and call $debug($bicycle);die; in the following order.

public function index() {
        $this->Bicycle->recursive = 2;
        $bicycles = $this->Paginator->paginate();
        $debug($bicycle);die;
        $this->set(compact('bicycles'));
    }

This will kill the model at this point and display an array of results returned. You will then see where the information you want is, and how to access it. Just remove the $debug line when finished.