开发者

CakePHP find related model data

I got classes User and Firm:

class Firm extends AppModel {
    var $name = 'Firm';
    var $belongsTo = 'User';
}

and:

class User extends AppModel {
    var $name = 'User';
   开发者_开发知识库 var $hasMany ='Post';
    var $hasAndBelongsToMany = 'Firm';
}

everything works fine, but how do I search Firm if user id = for example, 5? I used:

$this->set('firms',$this->Firm->User->find('all', array('conditions'=>array('User.id'=>'5'))));

and on my view i put:

<table>
    <tr>
        <th>Firma</th>
    </tr>
    <?php foreach($firms as $firm): ?>
    <tr>
        <td><?php echo $firm ['Firm']['firm_id']; ?></td>  //line 9
    </tr>
    <?php endforeach; ?>
</table>

But when I enter my view I get the error:

"Notice (8): Undefined index: firm_id [APP\views\firms\wylistuj.ctp, line 9]"


'firm_id' would be in your join table, not your Firm model.

If your looking to display the id of the current Firm, you should just need this

<td> <?php echo $firm['Firm']['id']; ?> </td>


You need to search like this:

$this->set('firms',$this->Firm->find('all',array('conditions'=>array('Firm.user_id'=>'5'))));

This should give you your wanted result.

Edit:

In case you want to associate your models with a "has and belongs to many" relationship you need to write your 2 models like this:

//user.php
class User extends AppModel {
    var $name = 'User';
    var $hasAndBelongsToMany = 'Firm';
}

//firm.php
class Firmextends AppModel {
    var $name = 'Firm';
    var $hasAndBelongsToMany = 'User';
}

To see how you can work with the association please read the manual section for HABTM (has and belongs to many) relationships.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜