Chris
Chris

Reputation: 644

CakePHP read in hasMany through relationship

Trying to display related data from a hasMany through table. It's finding the joinModel but not extending to the other table's data.

Item Model:

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

Groclist Model:

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

GroclistItem Model:

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

GroclistController View Action:

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));
}

Debug of $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
            )

    )

)

I would like the GroclistItem array to display the item data which should be a grocery list item such as Diet Coke or Soap. It's finding the correct associations in there.

Upvotes: 1

Views: 2978

Answers (1)

chetanspeed511987
chetanspeed511987

Reputation: 2025

GroclistController View Action:

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));
}

Upvotes: 3

Related Questions