[英]retrieve data from multiple tables in cakephp
i am using cakephp 2.xx. 我正在使用cakephp2.xx。 i have two tables in my database names and genders.
我的数据库名称和性别中有两个表。 i write innerjoin to display names with their gender.
我写了innerjoin来显示带有性别的名称。 gender is coming from genders table.
性别来自性别表。 my controller is below
我的控制器在下面
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)));
}
}
names model is 名称模型是
class Names extends AppModel {
var $belongsTo = 'Genders';
}
and genders model is 性别模型是
class Genders extends AppModel {
var $hasMany = 'Names';
}
and ctp code is 和ctp代码是
foreach ($gender as $post);
echo $post["names"]["Name"];
echo $post["genders"]["gender"];
this print Name fine. 此打印名称很好。 but doesn't print gender and result in Undefined index: genders.
但不会打印性别,并导致未定义索引:性别。 Please help
请帮忙
My recommendation, you don't have to follow it: Use singular names for models (Name, Gender). 我的建议是,您不必遵循它:对模型使用单数名称(名称,性别)。 This way it will automatically connect with the appropriate table (names, genders) and your models will be loaded automatically in their controllers (NamesController, GendersController).
这样,它将自动与适当的表(名称,性别)连接,并且您的模型将自动加载到其控制器(NamesController,GendersController)中。 If you don't follow this advice, change the code below accordingly (load the model manually as you did in your question and set $useTable in the model).
如果您不遵循此建议,请相应地更改以下代码(如在问题中一样手动加载模型,并在模型中设置$ useTable)。
Option 1: getting all names containing gender data: 选项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));
}
}
Option 2: getting genders containing all names that belong to them: 选项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));
}
}
Use debug($names) or debug($genders) in your view to see the output array structure. 在视图中使用debug($ names)或debug($ genders)可以查看输出数组的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.