在控制器中访问另一个CakePHP的模型的最佳方法是什么? [英] What is the best way to access another CakePHP's Model in a Controller?

查看:137
本文介绍了在控制器中访问另一个CakePHP的模型的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个控制器,如 Table1sController Table2sController
对应的模型: Table1sModel Table2sModel

Say I got two Controllers like this Table1sController, and Table2sController. With corresponding models: Table1sModel, Table2sModel.

Table1sController 中,我有:

$this->Table1sModel->action();

说我想要访问 Table2sModel

如何在 Table1sController 中执行类似的操作?
我在Table1sController中尝试过:

How is it possible to do something like this in Table1sController? I have tried this in Table1sController:

$this->Table2sModel->action();

但我收到如下的错误信息:

But I received an error message like this:


未定义的属性:Table1sController :: $ Table2sModel

Undefined property: Table1sController::$Table2sModel


推荐答案

如果您的模型已定义关联(hasMany等),那么您可以访问该模型的方法在Model1Controller中)与:

If your models have defined associations (hasMany, etc.), then you can access that model's methods (assuming you're in Model1Controller) with:

$this->Model1->Model2->method();

如果两个模型之间没有模型关联,但您想要使用Model2方法,可以在modelessage的$ uses属性中添加一个条目。请参见 http://book.cakephp.org/2.0/ en / controllers.html#components-helpers-and-uses

If there is no model association between the two models, but you want to be able to use the Model2's methods, you can add an entry in the $uses attribute of model1Controller. See http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses

最后,如果它是暂时连接(你不想加载其他模型,因为你只是很少去访问model2),请查看手册的关于创建/销毁关联的部分,在 http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

Finally, if it's a transitory connection (you don't want the overhead of loading other models every time, because you're only rarely going to access model2), check out the manual's section on creating / destroying associations on the fly, at http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

这篇关于在控制器中访问另一个CakePHP的模型的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆