Linking Models Together hasMany cakephp

230 Views Asked by At

I have two tables:

Group(id/groupname)

People(id/name/groupid)

Group has many People

In the Group model:

var $hasMany = array(
    'People' => array(
        'className' => 'People',
        'foreignKey' => 'groupid'
    )
);

Is this OK ???

I also want my Group index.ctp to display group and the people that belong to it. Does anybody know how to do this?

tks

1

There are 1 best solutions below

1
On BEST ANSWER

First: You need to use the proper naming conventions:

Group(id/name)

Person(id/name/group_id)

If you use the right naming conventions on your table, you can use cake bake to auto-generate models, views and controllers.

How to do this manually:

In your Group model, you need to set up your relationship:

public $hasMany = array(
    'Person' => array(
        'className' => 'Person',
        'foreignKey' => 'group_id'
    )
);

I'm presuming your GroupsController has the proper index function:

public function index() {
    $this->set('groups', $this->paginate());
}

Next, you need to display this all in your Groups/index.ctp. To do this, you loop through all the groups, and display each one. Each group will have all its people attached to it. If you aren't totally sure what kind of data your controller is passing to the view, you can do a debug($groups) in your view to see what the structure is like.

This is a VERY bare-bones way you can view all your users with your groups:

<table>
    <tbody>
    foreach($groups as $group){
        ?>
        <tr>
            <td><?php echo $group['Group']['name']; ?></td>
            <td>
                <?php foreach($group['Person'] as $person){
                    echo "<p>" . $person['name'] . "</p>";
                } ?>
            </td>
        </tr>
    <?php   
    }
    ?>
    <tbody>
<table>

You say you want to select a person's group when you create the person:

under PeopleController.php, make sure you have this in your add() function:

// Get a list of all groups
$groups => $this->Person->Group->find('list');
// 'set' the $groups array so it's accessible in your view
$this->set(compact('groups'));

And then, in your add.ctp view:

echo $this->Form->input('group_id', array());

CakePHP's magic should automatically populate the select box with your groups! Hope that helps!