使用 loadModel 时使用递归分页
在我的“报告”控制器(它只是一个没有任何实际数据库的虚拟控制器)中,我试图生成其他模型的分页视图。例如,为了生成“交易”模型的分页视图,我正在执行以下操作:
$this->loadModel('Transactions');
$this->Transactions->bindModel(array('belongsTo'=>array('Item'=>array('className'=>'Item'),'Member'=>array('className'=>'Member'))));
$results = $this->paginate('Transactions',null,array('recursive'=>1));
但这并没有为我提供来自项目和成员的关联数据。如果我这样做,
$this->Transactions->find('all',array('recursive'=>1))
我会得到关联的数据,但不会分页。我如何获得也包含关联数据的分页视图?
In my "Reports" controller, which is just a dummy controller without any actual database, I'm trying to generate a paginated view of other models. For example, to generate paginated view of "Transactions" model I'm doing the following:
$this->loadModel('Transactions');
$this->Transactions->bindModel(array('belongsTo'=>array('Item'=>array('className'=>'Item'),'Member'=>array('className'=>'Member'))));
$results = $this->paginate('Transactions',null,array('recursive'=>1));
But this is not giving me associated data from Items and Members. If I do a
$this->Transactions->find('all',array('recursive'=>1))
I get the associated data, but not paginated. How will I get paginated view which includes the associated data too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两件事:首先,即使复数模型名称可以出于某种奇怪的原因工作,惯例是模型名称是单数,例如
$this->loadModel('Transaction');
。请参阅命名约定手册。其次,忘记
递归
并转向Containable
行为。坦率地说,它非常有用,以至于我想知道为什么它不是默认进程(也许是因为 Containable 是在框架非常成熟时创建的)。马特有一本好书解释为什么 Containable 很好(下载它,真的,它几乎是强制性的:D)。但为了提供更多帮助,我将准确地告诉您如何解决包含性问题:1) 定义模型中的关联,例如:
在事务模型中:
在项目模型中:
对成员模型执行相同的操作。
2) 使用以下代码在
/app/
中创建app_model.php
文件:(AppModel 类中的
$actsAs
变量告诉所有模型使用 Containable)3) 在报表控制器中,将代码更改为如下所示:
(contain 参数是您想要包含的所有关联模型的数组。您可以仅包含一个关联模型,也可以包含所有关联模型,或者包含任何您想要的模型)。
就是这样!
Two things: First, even when plural model names can work for some odd reason, the convention is that model names are singular, like
$this->loadModel('Transaction');
. See the manual on naming conventions.Second, forget about
recursive
and go for theContainable
behavior. Frankly, it's so useful that I wonder why it isn't the default process (perhaps because Containable got created when the framework was very mature). Matt has a good book explaining why Containable is good (download it, really, it's almost mandatory :D ). But to help even more, I'm going to tell you exactly how you solve your issue with containable:1) Define the associations in the models, like:
In Transaction model:
In Item model:
Do the same for the Member model.
2) Create an
app_model.php
file in/app/
with this code:(The
$actsAs
variable here within the AppModel class tells all models to use Containable)3) In the Reports Controller, change the code to something like this:
(The contain parameter is an array of all the associated models that you want to include. You can include only one assoc. model, or all, or whatever you want).
And that's it!