简体   繁体   English

在CakePHP中使用多个数据库表

[英]Using multiple database tables in CakePHP

In my application, i have many methods that my controllers use commonly. 在我的应用程序中,我有许多控制器常用的方法。 At first i copied them to controllers, then i found out that i must put them in AppController. 起初我将它们复制到控制器,然后我发现我必须把它们放在AppController中。 So i. 所以我。 reach those methods from derived controllers by "$this->commonmethod" 通过“$ this-> commonmethod”从派生控制器中获取这些方法

The methods that i put into AppController creates different types of data, so i need to put them to 4-5 different tables in my database. 我放入AppController的方法会创建不同类型的数据,所以我需要将它们放到我的数据库中的4-5个不同的表中。 Most of the tables don't have a relation between each other. 大多数表彼此之间没有关系。

But most of my controllers will use that tables to fetch related data for them. 但是我的大多数控制器都会使用这些表来获取它们的相关数据。

(I checked the examples in cookbook, there are examples about Blogging, category and tags. Where tables have relation between them) (我检查了食谱中的例子,有关于博客,类别和标签的例子。表格之间有关系)

  1. Should i put my common controller code into a Plugin or Component? 我应该将我的通用控制器代码放入插件或组件吗? Or what would be the decision criteria? 或者决定标准是什么?
  2. Is it possible to use multiple database tables from a controller or a component? 是否可以使用来自控制器或组件的多个数据库表?
  3. Do Datasources or behaviours are suitable for this case. 数据源或行为是否适合这种情况。

Thank you in advance 先感谢您

Best way is (if possible) to redesign the database , because in cakephp a good database design resolve half of your problems. 最好的方法是(如果可能的话) 重新设计数据库 ,因为在cakephp中,一个好的数据库设计解决了一半的问题。 If this is not possible then second one is use Components and using this component you can you multiple database tables. 如果这不可能,那么第二个是使用组件 ,使用此组件,您可以使用多个数据库表。

It's hard to say what the best approach would be, given we don't know much about the database structure, what the controller methods do, and how they are used. 鉴于我们对数据库结构,控制器方法的作用以及如何使用它们知之甚少,很难说最佳方法是什么。

But one of your questions is very straightforward: 但你的一个问题非常简单:

Is it possible to use multiple database tables from a controller or a component? 是否可以使用来自控制器或组件的多个数据库表?

Yes, that is possible. 是的,这是可能的。 Just create a model for each table (use public $useTable = 'tablename if cake cannot detect the table name automatically from your model names). 只需为每个表创建一个模型(如果cake无法从您的模型名称中自动检测到表名,请使用public $useTable = 'tablename )。 Then, in AppController (considering your code will stay there), use this: 然后,在AppController (考虑到您的代码将保留在那里),使用此:

public $uses = array('List', 'all', 'models', 'you', 'need');

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

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