CakePHP三级分页协会

时间:2014-06-14 07:25:29

标签: cakephp model pagination associations

我在阅读了这本Cookbook和其他SO帖子之后有点困惑..

我有以下3级关系:

Project (has customer_id) -> Customer (has user_id) -> User 

我希望能够将用户条件传递到我的Projects paginate函数中。我怎样才能做到这一点?我认为我必须正确连接三个模型,而我目前没有这样做......


ProjectsController 看起来像是:

$this->paginate = array(
            'contain' => array('Customer' => array('User')),
            'order' => 'Project.id ASC',
            'conditions' => $condition,
            'limit' => $limit
        );

项目模型有:

public $belongsTo = 'Customer';

客户模式有:

public $belongsTo = 'User';
public $hasMany = array('Order', 'Project');

用户模型有:

public $hasOne = array(        
        'Customer' => array(
            'className' => 'Customer',
            'conditions' => array('User.role' => 'Customer'),
            'dependent' => false
        )

1 个答案:

答案 0 :(得分:0)

使用联接

唯一能够根据用户字段进行过滤/排序的方法是实现以下形式的sql:

SELECT
    ...
FROM 
    projects
LEFT JOIN
    customers on (projects.customer_id = customers.id) 
LEFT JOIN
    users on (customers.user_id = users.id)

如果仅用于此目的或过滤/排序 - 最简单的方法之一就是注入连接:

$this->paginate = array(
    'contain' => array('Customer'),
    'order' => 'Project.id ASC',
    'conditions' => $condition,
    'limit' => $limit,
    'joins' => array(
        array(
            'table' => 'users',
            'alias' => 'User',
            'type' => 'INNER',
            'conditions' => array(
                'Customer.user_id = User.id',
                // can also define the condition here
                // 'User.is_tall' => true 
            )
        )
    )
);

// only projects where the user is tall
$results = $this->paginate(array('User.is_tall' => true)); 

使用“异国情调”协会

或者,将关联直接从Project模型绑定到User模型:

$this->Project->bindModel(array(
    'belongsTo' => array(
        'User' => array(
            'foreignKey' => false,
            'conditions' => array(
                'Customer.user_id = User.id',
                // can also define the condition here
                // 'User.is_tall' => true 
            )
        )
    )
));

$this->paginate = array(
    'contain' => array('Customer', 'User'), // <- different
    'order' => 'Project.id ASC',
    'conditions' => $condition,
    'limit' => $limit
);

// only projects where the user is tall
$results = $this->paginate(array('User.is_tall' => true)); 

在任何一种情况下,执行的sql都将包含两个连接,一个依赖于另一个连接。