我尝试了3天你解决方案让它工作,但我需要帮助。大多数情况下,我做了尝试和错误。如果有人可以给我一个解决方案,我可以对其进行逆向工程并更好地理解cakephp。
我想要的是像这样的索引视图(制作图形): http://www.bilder-upload.eu/show.php?file=fd8e93-1340110385.png
门和钥匙有一个关系,我想列出所有属于1键的门
我有3张桌子:
门(id,title,txt) 键(ID,号,说明) doors_keys(door_id,KEY_ID)这是我的 key.php
<?php
class Key extends AppModel {
public $hasAndBelongsToMany = array ('Door');
public $displayField = 'description';
// containable
var $actsAs = array('Containable');
}
door.php
<?php
class Door extends AppModel {
public $name = 'Door';
public $belongsTo = array('Building');
//public $actsAs = array('Containable');
public $hasAndBelongsToMany = array('Key');
// validation array wird aufgemacht
public $validate = array(
// validation wird für das Datenbankfeld title definiert
'title' => array(
// Feld darf nicht leer sein
'rule' => 'notEmpty' ,
// Eintrag muss ausgewählt werden
'required' => true
),
// validation für das DB Feld building_id
'building_id' => array(
'rule' => 'notEmpty' ,
'required' => true
),
);
// viele türen sind in einem Gebäude-> n:1->$belongsTo
// in der tabelle doors muss ein fremdschluessel auf die andere datenbank angelegt sein
}
keyscontroller.php (不工作)
class KeysController extends AppController {
public function index() {
$this->paginate = array(
'contain' => array(
// we want to get the key
'Door' => array(
// the info i wanna know is in the field txt
'fields' => array('txt')
),
),
);
$keys = $this->paginate('Key');
debug($this->set(compact('keys')));
}
index.ctp from keys
<h2>Schluessel selbstgemacht</h2>
<table>
<!-- tr definiert eine Tabellenzeile -->
<tr>
<!-- th Überschriften in der Zeile -->
<th>ID</th>
<th>Description</th>
<th>number</th>
</tr>
<?php foreach($keys as $key): ?>
<tr>
<td><?php echo $key['Key']['id'] ?></td>
<td><?php echo $key['Key']['description'] ?></td>
<td><?php echo $key['Key']['number'] ?></td>
<td><?php echo $key['Door']['txt'] ?></td>
<td>
<?php echo $this->Html->link('Details', '/keys/view/' . $key['Key']['id']) ?>
<?php echo $this->Html->link('bearbeiten', '/keys/edit/' . $key['Key']['id']) ?>
<?php echo $this->Html->link('loeschen', '/keys/delete/' . $key['Key']['id']) ?>
</td>
</tr>
<?php endforeach; ?>
</table>
我想这是一个基本问题,但我无法找到解决方案。所以我需要一点帮助。感谢
答案 0 :(得分:0)
将'recursive' => 1
添加到您的Door-&gt; find()以获取相关密钥的数据:
class KeysController extends AppController {
public function index() {
$doors = $this->Door->find(
'recursive' => 1
);
$this->set('doors', $doors);
// Look at the result
debug($doors);
}
但是,如果模型关系复杂,使用recursive
会变得非常混乱。建议您在模型上使用ContainableBehavior。