【问题标题】:CakePHP 3rd Level Association for PaginationCakePHP 3 级分页关联
【发布时间】:2014-08-04 17:45:11
【问题描述】:

在这里阅读 Cookbook 和其他 SO 帖子后,我有点困惑..

我有以下3级关系:

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

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


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
        )

【问题讨论】:

  • I want to pull out the User data into the parent "level": - 很容易做到,但是:为什么?
  • 它可以让我更轻松地使用 Paginate 功能。我正在尝试对用户数据的项目视图进行分页。
  • 所以你想跨 3 个表加入 - 你为什么不问怎么做,而不是听起来像表面上的改变?
  • 是的,你是对的,我不知道我为什么要这样陷害它。我会改写它!

标签: cakephp model pagination associations


【解决方案1】:

使用连接

能够根据用户字段进行过滤/排序唯一需要做的就是实现以下形式的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 都将包含两个连接,一个依赖于另一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2011-06-17
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    相关资源
    最近更新 更多