在cakephp中,我如何设置一个模型的条件,该模型与我正在分页的模型没有关联,但与哪个模型相关联?

时间:2010-09-27 20:50:50

标签: cakephp pagination associations models cakephp-1.3

我在“客户”模型上分页($ this-> Customer-> paginate())。

客户模型与“联系”模型相关联,而“联系”模型又与“ContactAddress”模型相关联。

所以:

客户有多个联系人

联系belongsTo联系地址

现在我想使用搜索查询对'Customers-> index()'中的客户进行分页,让我们说'ContactAddress.city'LIKE'%New%'

我该怎么做?当我在paginate的条件下执行它时,它会在“where子句”中逻辑地说“未知列'ContactAddress.city'。

2 个答案:

答案 0 :(得分:0)

在任何情况下,两次移除的条件都很难,不管蛋糕与否。您需要逐步执行此操作(首先查找ContactAddresses并关联Contact.customer_ids,然后在Customer.id IN ($customer_ids)上分页),或者您需要使用子查询执行此操作。请参阅manual on how to do subqueries properly(它不是很漂亮)。

什么更好取决于您的编码技能,数据库大小和生成的查询的复杂性。测试两者并确定哪些对您有用。

答案 1 :(得分:0)

我找到了一个非常令人满意的解决方案。

我查看了分页功能的复杂代码,并在逻辑上发现,paginate设置条件并将这些条件传递给模型的查找函数(除非模型具有自己的'paginate'函数)。

我首先尝试覆盖paginate函数,但这太复杂了。我最终找到的解决方案是将连接传递给paginate的选项,就像在模型上'find'时传递它们一样:

    //Set the pagination options:   
    `$this->paginate = array(
        'limit' => 25,
        'order' => array(
        'Customer.lastname1' => 'asc'
        ),
        'joins' =>
        array(
                // OUTER JOIN because I wanted to also 
                // fetch record that do not have a 'contact'
        array(
            'table' => 'contacts',
            'alias' => 'Contact',
            'type' => 'LEFT OUTER',
            'conditions' => array(
                'Customer.id = Contact.customer_id',
                'Contact.class' => 'ContactAddress'
            )
            ),
        array(
            'table' => 'contact_addresses',
            'alias' => 'ContactAddress',
            'type' => 'LEFT OUTER',
            'conditions' => array(
                'Contact.index = ContactAddress.id',
            )
            ),
        ),
        // In your conditions you can now use any table that 
        // was joined as well as the original 'customer' table.
        'conditions' => $conditions,

    );

    $this->set('customers',$this->paginate('Customer'));

无论哪种方式,我希望这有助于某人!

相关问题