【问题标题】:Cakephp multiple belongsto fieldsCakephp 多个所属字段
【发布时间】:2013-09-09 23:54:59
【问题描述】:

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

我在 2 上使用递归

用户模型:

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

图书馆模型:

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 列。 请问我的错在哪里?

【问题讨论】:

    标签: cakephp-1.3 belongs-to


    【解决方案1】:

    您可能会发现使用 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;    
    }
    

    用户.php

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

    库.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( ... )
            );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多