cakephp包含两次模型关联

时间:2014-10-11 14:14:06

标签: cakephp associations containable

我必须从posts

获取数据

foreign keys
 category_id categories.id提到created_by  users.idupdated_by的引用,  users.idcreated_by的引用  )

我可以抓取username $this->Post->Behaviors->load('Containable'); $this->paginate = array( 'conditions' => array('Post.category_id' => $id), 'order' => array('title'), 'contain' => array( 'User'=>array( 'fields'=>array('id','first_name','last_name','username'), 'conditions' => array('User.id = Post.created_by') ), //posts table has 2 fields(created_by & updated_by) associated with users table //'User'=>array( // 'fields'=>array('id','first_name','last_name','username'), // 'conditions' => array('User.id = Post.updated_by') // ), 'Category'=>array( 'Type'=>array( 'fields'=>array('id','type_name') ) ), ) ); 但不能同时抓取

 public $belongsTo = array(
    'User'=> array(
        'className' => 'User',
        'foreignKey' => 'created_by',
        'foreignKey' => 'updated_by'
    ),

); 

//发布模型

public $hasMany = array(
    'Post' => array(
        'className' => 'Post',
        'foreignKey' => array('created_by','updated_by'),
    ),
);

//用户模型

created_by

如何将用户同时显示为(updated_by& {{1}})

1 个答案:

答案 0 :(得分:2)

首先,您需要在Post模型中定义两个关系

public $belongsTo = array(
    'CreatedUser'=> array(
        'className' => 'User',
        'foreignKey' => 'created_by'
    ),
    'UpdatedUser'=> array(
        'className' => 'User',
        'foreignKey' => 'updated_by'
    )
);

现在在用户模型中创建逆向关系。

public $hasMany = array(
    'CreatedPosts' => array(
        'className' => 'Post',
        'foreignKey' =>'created_by'
    ),
    'UpdatedPosts' => array(
        'className' => 'Post',
        'foreignKey' => 'updated_by'
    ),
);

然后是find()

$this->Post->Behaviors->load('Containable');

$this->paginate = array(
        'conditions' => array('Post.category_id' => $id),
        'order' => array('title'),
        'contain' => array(
            'CreatedUser'=>array(
                    'fields'=>array('id','first_name','last_name','username')
                ),
            'UpdatedUser'=>array(
                    'fields'=>array('id','first_name','last_name','username')
                ),
            'Category'=>array(
                'Type'=>array(
                    'fields'=>array('id','type_name')
                    )
                ),
        )
    );