我正在使用cakephp 2.xx.我的数据库名称和性别有两个表。我写内心连接以显示他们的性别名称。性别来自性别表。我的控制器在
之下class NamesController extends AppController {
public $helpers = array("Html", "Form");
public function index() {
$this->loadModel("names");
$query_options = array();
$query_options["fields"] = array("names.Name","genders.gender");
$query_options["joins"] = array("table" => "genders", "alias" => "genders", "type" => "INNER", "conditions" => array("genders.id = names.Gender_id",));
$this->set("gender", $this->names->find('all', array($query_options,'limit' => 10 ,'recursive' => 1)));
}
}
名称模型是
class Names extends AppModel {
var $belongsTo = 'Genders';
}
和性别模型是
class Genders extends AppModel {
var $hasMany = 'Names';
}
和ctp代码是
foreach ($gender as $post);
echo $post["names"]["Name"];
echo $post["genders"]["gender"];
此打印名称很好。但不打印性别并导致未定义的索引:性别。请帮忙
答案 0 :(得分:1)
我的建议,您不必遵循它:对模型使用单数名称(名称,性别)。这样它将自动连接相应的表(名称,性别),你的模型将自动加载到他们的控制器(NamesController,GendersController)。如果您不遵循此建议,请相应地更改以下代码(如您在问题中手动加载模型并在模型中设置$ useTable)。
选项1:获取包含性别数据的所有名称:
class NamesController extends AppController {
public function index() {
$this->Name->Behaviors->load('Containable');
$query_options = array(
'fields' => array("Name.name"),
'contain' => array(
'Gender' => array(
'fields' => array('Gender.gender'),
),
),
);
$this->set("names", $this->Name->find('all', $query_options));
}
}
选项2:让性别包含属于它们的所有名称:
class NamesController extends AppController {
public function index() {
$this->Name->Gender->Behaviors->load('Containable');
$query_options = array(
'fields' => array("Gender.gender"),
'contain' => array(
'Name' => array(
'fields' => array('Name.name'),
),
),
);
$this->set("genders", $this->Name->Gender->find('all', $query_options));
}
}
在视图中使用debug($ names)或debug($ genders)来查看输出数组结构。