对不起我的英语,我是使用 CAKEPHP 2.3 的新手
我在使用模型关联时遇到问题,我无法获得“加入数据”(我知道如果模型设置好,cakephp 会自动加入数据,显然我做错了)
我的数据库中有 2 个表:
部门(以下列)
-ID
-姓名
-region_id ( region_id 是 region(id) 的外键)
地区(以下列)
-ID
-姓名
我在 cakePhp 中制作了两个模型:
区域.php
<?php
class Region extends AppModel {
var $name = 'Region';
var $actsAs = array( 'Containable' );
public $hasMany = array(
'Departement' => array(
'className' => 'Departement',
'foreignKey' => 'region_id',
'dependent' => false
)
);
}
?>
部门.php
<?php
class Departement extends AppModel {
var $name = 'Departement';
var $actsAs = array( 'Containable' );
public $belongsTo=array(
'Region' => array(
'className' => 'Region',
'foreignKey' => 'region_id',
'dependent' => false
)
);
}
?>
在我需要部门和地区的另一个控制器中,我尝试了很多想法,但在你的想法之后,我需要你的帮助!
我这样做:第一次尝试:
<?php
class SignalementsController extends AppController {
public $helpers = array('Html', 'Form');
var $name = 'Signalements';
var $uses = array('Signalements','Regions','Departements','Communes');
public $recursive = 4;
public function index() {
$departements = $this->Departements->find('all');
$this->set('departements', $departements);
}
}
who 在索引视图中输出:
array(
(int) 0 => array(
'Departements' => array(
'id' => '1',
'name' => 'AIN',
'region_id' => '82'
)
),
(int) 1 => array(
'Departements' => array(
'id' => '10',
'name' => 'AUBE',
'region_id' => '21'
)
)
...
)
但是没有自动加入的区域
第二次尝试:我将查找模型从
$regions = $this->Regions->find('all');
$this->set('regions', $regions);
谁输出:
array(
(int) 0 => array(
'Regions' => array(
'id' => '11',
'name' => 'ILE-DE-FRANCE'
)
), ... );
但没有自动加入的部门
最后的
$fields=array('Region.id','Region.nom','Departement.id','Departement.nom');
$all= $this->Regions->Departements->find('all',$fields);
/* or all this not working as execpted
$all= $this->Departements->Regions->find('all',$fields);
$all= $this->Departements->find('all',$fields);
$all= $this->Regions->find('all',$fields);
*/
$this->set('all', $all);
我尝试获取每个部门内的区域数据,例如这样
array(
(int) 0 => array(
'Departements' => array(
'id' => '1',
'nom' => 'AIN',
'region' => array( 'id' => '82', 'nom' => 'POITOU-CHARENTES')
)
),
但我只得到这个:
array(
(int) 0 => array(
'Departements' => array(
'id' => '1',
'nom' => 'AIN',
'region_id' => '82'
)
),
如果您有任何想法,请留下,非常感谢