Cakephp多个belongssto字段

时间:2013-09-09 23:54:59

标签: cakephp-1.3 belongs-to

我正在使用Cakephp 1.3,我遇到了多个belongsTo关系的问题。 我有3个表库,用户,地址。

我在2上使用递归

的usermodel:

var $belongsTo = array('address'=>array('className'=>'address','foreignKey'=>'users_id'));

LibraryModel:

var $belongsTo = array('user' => array('className'=> 'user','foreignKey'=>'user_id'));

function getUser($idBook)
    {
        $this->recursive = 2;
        return $this->find('all',
    array('conditions'=>array('library.book_id'=>$idBook),
'fields'=>array('user.id','user.nick','address.town')));
    }

它只在没有字段参数的情况下工作,但我想只选择这3列。 请问我的错误在哪里?

1 个答案:

答案 0 :(得分:0)

你可能会发现使用Containable更容易http://book.cakephp.org/1.3/en/The-Manual/Core-Behaviors/Containable.html我还建议使用懒惰模型插件https://github.com/Phally/lazy_model

app_model.php

App::import( 'Lib', 'LazyModel.LazyModel' );
class AppModel extends LazyModel {
    var $actsAs = array( 'Containable' );
    var $recursive = -1;    
}

user.php的

class User extends AppModel {
    var $name = 'user';
    var $belongsTo = array(
        'Address' => array(
            'className' => 'Company',
            'foreignKey' => 'users_id'
        )
    );
}

library.php

class Library extends AppModel {
    var $name = 'library';
    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        )
    );

    function getUser( $idBook )
    {
        return $this->find( 'all', array(
            'conditions'=>array('library.book_id'=>$idBook),
            'contain' => array(
                'user' => array(
                    'address' => array(
                       'fields' => array( ... )
                    ),
                    'fields' => array( ... )
                )
            ),
            'fields' => array( ... )
        );
    }
}