Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp: BelongsTo Relationship

Tags:

cakephp

I want to model the following simple relationship:

One Passenger belongs to a Car; One Car has many Passengers.

The passenger table has an id and Car_id column, the Car table has one id column.

My models look like this:

<?php
class Passenger extends AppModel {
   var $name = 'Passenger';
   var $belongsTo = 'Car';
} ?>

and

<?php
class Car extends AppModel {
   var $name = 'Car';
   var $hasMany = array (
      'Passenger' => array (
            'className' => 'Passenger',
            'foreignKey' => 'car_id'
         )
   );
}
?>

and my add Passenger .ctp looks like this:

<?php
echo $this->Form->create('Passenger');
    echo $this->Form->input('car_id');
    echo $this->Form->end('Save');
?>

BUt when I access the page to add a passenger, all I see is an empty drop down box. Is there an additional step I must take in order to populate the dropbox with all cars?

like image 899
Chris Avatar asked Oct 14 '22 19:10

Chris


2 Answers

First off, you have forgotten to mention the belongsTo relation in your Passenger model:

<?php
class Passenger extends AppModel {
   var $name = 'Passenger';
   var $belongsTo = array('Car');
}
?>

Next, in the corresponding action of your controller, you will need to obtain a list of all the cars from the database, and set it to the plural form of the model's variable ($cars). You would do that like so:

$cars = $this->Passenger->Car->find('list');
$this->set(compact('cars'));

This will convert the car_id input field into a drop down list with the populated information.

HTH.

like image 196
RabidFire Avatar answered Oct 30 '22 01:10

RabidFire


The Passenger will only know about the car with which it is associated - at this point, none.

In the add method in the passenger controller, do

$this->Car->find('list');

and pass the result into your view:

$this->set('cars',$cars);

In the view, give the $cars variable as the value for $options in the field declaration:

echo $this->Form->input('car_id', array('options' => $cars));

Alternatively, you can do something like:

echo $this->Form->input('Car.id', array('options' => $cars));
like image 24
Leo Avatar answered Oct 30 '22 00:10

Leo