简体   繁体   English

如何根据cakephp中其他表的结果从数据库表中获取结果?

[英]How do I get results from a database table based on results from a different table in cakephp?

For example I have the following tables in my database: 例如,我的数据库中有以下表格:

  • People
  • Groups 团体

And in the People table I have the following columns: 人员表中,我有以下几列:

  • Name 名称
  • Birthdate 生日
  • Group

In the Groups table I have the following columns: 在“ 组”表中,我具有以下列:

  • Name 名称
  • Colour 颜色

Now I want to fetch results from my database to make a list of all the People . 现在,我想从数据库中获取结果以列出所有人员 So I would use this: 所以我会用这个:

$this->set('people', $this->Person->find("all"));

And obviously in my view I would loop through the returned array and display it. 而且显然在我看来,我将遍历返回的数组并显示它。 Now I also want to find out for each person in the list what Colour and Group name they are (retrieved from the groups table). 现在,我还想为列表中的每个人找出他们的颜色和组名(从表中检索)。

How would I go about this in CakePHP. 我将如何在CakePHP中进行此操作。

First make sure your model relationships are defined. 首先确保定义了模型关系。 Second, you might want to consider using "id" fields for your related tables (I assume you did and maybe just did not include them in your original questions table definitions). 其次,您可能要考虑在相关表中使用“ id”字段(我假设您已经这样做,也可能只是没有在原始问题表定义中包括它们)。

And yes, run debug ($this->Person->find("all")) as Elwhis noted to see what your array is dumping out. 是的,按照Elwhis的说明运行debug ($ this-> Person-> find(“ all”)),以查看您的数组正在转储什么。

And if this is a mission critical application, be sure to use containable instead of recursive to prevent taxing queries to your db. 并且,如果这是一个关键任务应用程序,请确保使用containable而不是递归,以防止对数据库进行查询。

You have to set the recursive attribute. 您必须设置recursive属性。 But I guess it should work with the default value. 但是我想它应该可以使用默认值。 Put this line in your controller debug($this->Person->find("all")) and check whether the data doesn't already contain you desired group information. 将此行放入控制器debug($this->Person->find("all"))然后检查数据是否尚未包含所需的组信息。

If not, try setting $this->Person->recursive = 1; 如果不是,请尝试设置$this->Person->recursive = 1; before calling the find() function 在调用find()函数之前

For more information about recursive : http://book.cakephp.org/view/1063/recursive 有关recursive更多信息: http : //book.cakephp.org/view/1063/recursive

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM