开发者

Cakephp: BelongsTo Relationship

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开发者_StackOverflow = '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?


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.


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));


$this->CompanyCashback->bindModel(array('belongsTo' => array(
        'CompanyBranch' => array('className' => 'CompanyBranch', 'foreignKey' => false, 'conditions' => array('CompanyCashback.publisher_id = CompanyBranch.publisher_id && CompanyBranch.branch_type = "online" ')),
        'PersonalInformation' => array('className' => 'PersonalInformation', 'foreignKey' => false, 'conditions' => array('CompanyCashback.publisher_id = PersonalInformation.user_id')),
        'Country' => array('className' => 'Country', 'foreignKey' => false, 'conditions' => array('PersonalInformation.country_id = Country.id')),
        'User' => array('className' => 'User', 'foreignKey' => false, 'conditions' => array('PersonalInformation.user_id = User.id')))
));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜