2012-02-20 54 views
1

试图通过表显示hasMany中的相关数据。它找到joinModel但不能扩展到其他表的数据。CakePHP读取hasMany通过关系

产品型号

class Item extends AppModel { 
public $name = 'Item'; 
    public $belongsTo = array('Category'); 
    public $hasMany = array('GroclistItem'); 
} 

Groclist型号

class Groclist extends AppModel { 
public $name = 'Groclist'; 
    public $belongsTo = array('Category'); 
    public $hasMany = array('GroclistItem'); 
} 

GroclistItem型号

class GroclistItem extends AppModel { 
public $name = 'GroclistItem'; 
    public $belongsTo = array('Groclist', 'Item'); 
    public $useTable = 'groclists_items'; 
} 

GroclistController查看操作

public function view($id = null) { 
    if (!$id) { 
     $this->Session->setFlash(__('Invalid list', true)); 
     $this->redirect(array('action' => 'index')); 
    } 
    $this->set('groclist', $this->Groclist->read(null, $id)); 
} 

的$ groclist调试:

app\View\Groclists\view.ctp (line 80) 
Array 
(
[Groclist] => Array 
    (
     [id] => 3 
     [name] => This Week 
     [user_id] => 
     [sunday] => Pizza 
     [monday] => Scallops 
     [tuesday] => Stuffed Mushrooms 
     [wednesday] => Mustard Chicken with Daulphanois Potatoes 
     [thursday] => Sizzling Chicken and Cheese 
     [friday] => Walkabout Soup with Beer Bread 
     [saturday] => Paradise Indian 
     [created] => 2011-09-15 14:42:55 
     [modified] => 2012-02-19 16:51:00 
    ) 

[GroclistItem] => Array 
    (
     [0] => Array 
      (
       [id] => 18 
       [item_id] => 24 
       [groclist_id] => 3 
      ) 

     [1] => Array 
      (
       [id] => 17 
       [item_id] => 23 
       [groclist_id] => 3 
      ) 

    ) 

) 

我想GroclistItem阵列来显示这应该是一个购物清单的项目,如健怡可乐或项目数据肥皂。它在那里找到正确的关联。

+0

为什么你有一个项目模型和GroclistItem模式?如果GroclistItem是特定类型的Item,那么Groclist当然应该有很多项目呢? – swiecki 2012-02-20 04:16:05

+0

您的GroclistItem表看起来像hasAndBelongsToMany关系的连接表 – papachan 2012-02-20 04:20:16

回答

3

GroclistController查看行动:

public function view($id = null) { 
if (!$id) { 
    $this->Session->setFlash(__('Invalid list', true)); 
    $this->redirect(array('action' => 'index')); 
} 
$this->Groclist->recursive =2; 
$this->set('groclist', $this->Groclist->read(null, $id)); 
} 
+0

此方法可以工作,但是在添加15个项后,它现在正在执行32个数据库查询,耗时约8毫秒。我的问题是这个比例有多好? – Chris 2012-02-20 15:54:02

+0

然后你必须使用包含:http://book.cakephp.org/1.3/view/1323/Containable或使用unBindModel:http://book.cakephp.org/1.3/view/1045/Creating-and-Destroying -Associations上即时 – chetanspeed511987 2012-02-21 03:37:54