CakePHP通过关系读取hasMany

时间:2012-02-20 03:09:49

标签: cakephp

尝试从hasMany到表中显示相关数据。它找到了joinModel,但没有扩展到其他表的数据。

项目模型

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数组显示项目数据,这些数据应该是一个杂货清单项目,例如Diet Coke或Soap。它在那里找到了正确的关联。

1 个答案:

答案 0 :(得分: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));
}