2010-09-27 133 views
0

我在'客戶'模型上分頁($ this-> Customer-> paginate())。在cakephp中,我如何設置一個模型的條件,該模型與我正在分頁的模型沒有關聯,但與哪個模型相關聯?

客戶模型與'Contact'模型相關聯,而'Contact'模型又與'ContactAddress'模型關聯。

所以:

客戶的hasMany聯繫

聯繫屬於關聯ContactAddress

現在我想用一個搜索查詢假設進行分頁客戶在 '客戶 - >指數()'「ContactAddress.city 'LIKE'%New%'

我該怎麼做?當我在分頁的條件下執行時,它會說:「邏輯上」where子句「中的未知列'ContactAddress.city'。

回答

0

我找到了非常滿意的解決方案。

我翻看了分頁功能的複雜代碼,發現邏輯上,paginate設置條件並將它們傳遞給模型的查找函數(除非模型具有自己的「分頁」函數)。

我首先嚐試覆蓋paginate函數,但這太複雜了。我最終找到了解決辦法是通過在連接到PAGINATE的選項,就像你在做模型時,「發現」通過他們:

//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')); 

無論哪種方式,我希望這可以幫助別人!

0

在兩次移除的情況下進行分頁很困難,無論如何也不行。您或者需要分步執行(首先找到ContactAddresses和關聯的Contact.customer_ids,然後在Customer.id IN ($customer_ids)上分頁),或者您需要通過子查詢來完成。看到manual on how to do subqueries properly(這不是很漂亮)。

更好的方法取決於您的編碼技巧,數據庫大小和查詢結果的複雜性。測試兩者,並決定哪些適合你。

+0

感謝您的回答。 – Mosselman 2010-09-28 12:00:36

+0

查詢本身不是很麻煩,我創建了我想要的純SQL查詢。麻煩的是讓蛋糕做到這一點。 查詢:| SELECT * FROM 客戶爲卡斯特 LEFT JOIN聯繫人作爲續 ON cust.id = cont.customer_id LEFT JOIN contact_addresses爲addr ON cont.index = addr.id WHERE cont.class = 'ContactAddress' 和ADDR .city LIKE'%% Brus%'; | 它工作得很好。 – Mosselman 2010-09-28 12:06:20

+0

有一些像linkable這樣的行爲可以幫助你。與std蛋糕你是不幸的 – dogmatic69 2010-09-28 19:51:00