CakePHP与has_many上的条件分页 [英] CakePHP Pagination with conditions on has_many

查看:158
本文介绍了CakePHP与has_many上的条件分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个User表和一个历史表与用户hasMany Histories,我试图在用户表上实现分页。

So I have a User table and a History table with User hasMany Histories, and I'm trying to implement pagination on the user table.

我的问题是,我有搜索,一些可以搜索的东西是在历史表中的东西。有没有办法根据hasMany关联的表中的数据过滤分页结果? Containable,它最初看起来像一个解决方案,允许这种过滤,但只在检索相关数据,而不是记录本身(除非我缺少一些东西?)

My problem is that I have search, and some of the things one can search by are things in the History table. Is there a way to filter pagination results based on data in a table associated by hasMany? Containable, which initially seemed like a solution, allows such filtering but only in the retrieval of associated data, not the records themselves (unless I'm missing something?)

推荐答案

因为它是一个hasMany关系,这意味着Cake需要做2个单独的查询:1在users表上,一个在history表上检索所有的关联。由于在第2次查询之前未检索历史数据,因此无法通过WHERE条件筛选在历史记录模型中找到的字段的第1个查询。

Since it's a hasMany relationship, that means Cake will need to make 2 separate queries: 1 on the users table, and one on the histories table to retrieve all the associations. Since the History data isn't being retrieved until the 2nd query, then your 1st query cannot be filtered via WHERE conditions for fields found in the History model.

若要解决此问题,您可以执行以下两项操作之一:

To resolve this, you can do one of two things:


  1. 使用Containable在历史记录上执行分页(因为历史记录属于用户,

  1. Perform pagination on History using Containable (since History belongsTo User, meaning only 1 query will be performed).

对用户执行分页操作,除非执行特别加入历史记录,使其不再是有许多关系。

Perform pagination on User the way you're already doing, except perform an ad-hoc join to History such that it's no longer a hasMany relationship.

例如:

$this->User->bindModel(array('hasOne' => array('History')));
$this->paginate['User']['contain'][] = 'History';
$this->paginate('User', array('History.some_field' => 'some_value'));

这篇关于CakePHP与has_many上的条件分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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