2011-04-08 113 views
1

我正在嘗試基於相關模型中的字段進行搜索。我可以使用belongsTo模型,但不能使用hasMany模型。我確信這是簡單的我忽略但我看不到它。有人能指出我正確的方向(甚至是我需要的蛋糕冊頁 - 搜索,但沒有發現任何看起來像這樣的東西)。由於CakePHP:根據相關模型中的字段檢索記錄

在組控制器:(這不起作用)

$group = $this->Group->find('all', array('conditions' => array('Voucher.id' => '55'))); 

這並不:

$group = $this->Group->find('all', array('conditions' => array('TourOperator.id' => '3'))); 

背景文件片段:

組型號:

var $belongsTo = array(
     'TourOperator' => array(
      'className' => 'TourOperator', 
      'foreignKey' => 'tour_operator_id', 
      'conditions' => '', 
      'fields' => '', 
      'order' => '' 
     ) 
    ); 

    var $hasMany = array(
     'Voucher' => array(
      'className' => 'Voucher', 
      'foreignKey' => 'group_id', 
      'dependent' => true, 
      'conditions' => '', 
      'fields' => '', 
      'order' => 'Voucher.date, Voucher.meal_type_id'   
     ) 
    ); 

優惠券型號:

var $belongsTo = array(
     'Group' => array(
      'className' => 'Group', 
      'foreignKey' => 'group_id', 
      'conditions' => '', 
      'fields' => '', 
      'order' => '' 
     ) 
    ); 

旅遊經營模式:

var $hasMany = array(
    'Group' => array(
     'className' => 'Group', 
     'foreignKey' => 'tour_operator_id', 
     'dependent' => false, 
     'conditions' => '', 
     'fields' => '', 
     'order' => '', 
     'limit' => '', 
     'offset' => '', 
     'exclusive' => '', 
     'finderQuery' => '', 
     'counterQuery' => '' 
    ) 
); 

更新(如張貼在評論如下,但更清晰的讀到這裏)

我已經結束了使用此。

$groups = $this->Group->Voucher->find('all', array('fields' => 'DISTINCT group_id', 'conditions' => array('Voucher.status' => 'pending'))); 
$group_ids = Set::extract($groups, '/Voucher/group_id'); 
$data = $this->Group->find('all', array('conditions' => array('Group.id' => $group_ids))); 

我得到我的匹配標準組ID的不同列表,創建只是一組ID,然後用它來拉組,使我希望他們在我看來,陣列是有序的。

回答

0

你能重鑄查詢到$this->Voucher->find,然後使用從該查詢返回的相關數據進行分組?正如你所說,通過他們的TourOperator id找到組是沒有問題的,而Groups/Voucher關係看起來好像是相反的。

+0

我正在考慮嘗試沿着這些方向行事。返回的數組是凌亂的工作與我的目的,但讓我思考,我已經結束了使用它。 '$ groups = $ this-> Group-> Voucher-> find('all',array('fields'=>'DISTINCT group_id','conditions'=> array('Voucher。status'=>'pending'))); \t \t $ group_ids = Set :: extract($ groups,'/ Voucher/group_id'); \t \t $ data = $ this-> Group-> find('all',array('conditions'=> array('Group.id'=> $ group_ids)));' 我得到一個清晰的列表組ID,然後使用這些組來拉動組,以便按照我的預期在陣列中排列陣列。 – 2011-04-09 04:01:09

0

使用CakePHP的Containable行爲,您不能在hasMany和hasAndBelongsToMany關聯中使用相關數據的條件。這是因爲它使用單獨的查詢來獲得這些關聯。

但是,使用可鏈接行爲,您可以使用來自hasMany關聯的數據來過濾記錄。行爲可以在這裏下載:https://github.com/Terr/linkable

Linkable使用標準JOIN來加入相關數據。這意味着它不會像所有正常的SELECT一樣提取所有相關數據(即所有與您的組相關的優惠券)。但是,它可以與Containable一起執行這兩個操作。

您可以在README中找到Linkable如何工作的示例。

(聲明:我目前維持聯性,但是這不是我點的原因吧)

+0

感謝您的鏈接Terr,我也會看看Linkable。 – 2011-04-09 04:10:22

相關問題