CakePHP $belongsTo not working

大兔子大兔子 提交于 2019-12-14 03:15:55

问题


I am having a hell of a time getting my association to work here. every time I run the view action on the Events controller, and use var_dump, I just get back the event info, and no company info, it's like its ignoring my association all together, and whats even more annoying is there is no error messages.

the Events table has a field called Company_ID, and the Companies table has an ID field. (yes upper case Company_ID, and ID).

class Event extends AppModel{
    public $name = "Events";
//    public $belongsTo = 'Company';
    public $belongsTo = array('Company'=>array(
        'className' => 'Company',
        'foreignKey'=>'Company_ID'
    ));
    //public $hasOne = 'Company';
    /*public $hasOne = array('Company'=>array(
        'className' => 'Company',
        'foreignKey'=>'Company_ID'
    ));*/
}

App::uses("AppModel", "Model");
class Company extends AppModel{
    public $name = "Company";
}

The calling controller.

public function view() {
    $id = $this->request->params['id'];
    $this->set(
        'event', 
        $this->Event->find(
            'first', 
             array('conditions' => array('Event.id' => $id))
        )
    );
}

回答1:


possible duplicate of CakePHP does not save associated Models. see This is by far the most common cause of "why is my model logic not being executed" questions.

It was the file names, some of them where the plural form vs. singular. I changed Events.php to Event.php and Companies.php to Company.php that seemed to do the trick.




回答2:


Can you please try the following:

This may help you

 public $belongsTo = array('Company'=>array(
    'className' => 'Company',
    'foreignKey'=>'company_id'
));

Thanks



来源:https://stackoverflow.com/questions/22139097/cakephp-belongsto-not-working

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