CakePHP 使用 CRUD 插件对数据库视图进行分页

CakePHP Paginating Database Views with CRUD Plugin

瞄准

使用 Cake2.x 和 CRUD 插件我需要查询和分页两个不同的模型

方法

我在模型文件中编写了一个数据库视图,它对我希望合并和分页的两个模型执行联合:

App::uses('ConnectionManager', 'Model');
App::uses('AppModel', 'Model');
App::uses('CakeLog', 'Log');

class Search extends AppModel {

    public function __construct() {
        parent::__construct();

        $connection = ConnectionManager::getDataSource('default');
        $return = $connection->execute("CREATE OR REPLACE VIEW `search` AS
            SELECT Post.id, 'post' AS `type` FROM `posts` AS `Post` 
            UNION 
            SELECT Product.id, 'product' AS `type`  FROM `products` AS `Product`");

        $return = ($return == true)?'Search View created successfully on '.date('Y-m-d H:i:s'):$return;
        CakeLog::write('search', $return);
    }

    public $useTable = 'search';// This model does not use a database table
    public $primaryKey = 'id'; // Define primary key
    public $useDbConfig = 'default'; // Define db

问题

我似乎无法对数据库视图进行分页,这是我在我的用户控制器中所做的:

$this->loadModel('Search'); // executes the database view SQL
return $this->Crud->execute();

然而,所有这一切都是对用户模型而不是我的视图进行分页。所以我似乎在某处错过了关键步骤。

如有任何帮助,我们将不胜感激。

this is what I am doing in my Users controller:

$this->loadModel('Search'); // executes the database view SQL

调用 loadModel 不会修改将要使用的 table Crud - 它只会使模型 Search 在控制器操作中可用。

更改 modelClass 属性

Crud Index 操作仅调用 paginate - 在用户控制器中,默认情况下,它将对 User 模型进行分页。要分页不同的 table - 最简单的方法是将 modelClass property 设置为该模型名称:

$this->modelClass = 'Search';
$this->Crud->execute();

Crud 然后应该对 Search 模型进行分页。