【问题标题】:CakePHP Paginating Database Views with CRUD PluginCakePHP 使用 CRUD 插件对数据库视图进行分页
【发布时间】:2016-12-09 08:53:08
【问题描述】:

瞄准

使用 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

问题

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

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

然而,这一切只是对用户模型进行分页,而不是对我的视图进行分页。所以看来我在某处遗漏了一个关键步骤。

任何帮助将不胜感激。

【问题讨论】:

    标签: cakephp pagination crud


    【解决方案1】:

    这就是我在用户控制器中所做的事情:

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

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

    更改modelClass 属性

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

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

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

    【讨论】:

    • 谢谢,我按照你的建议尝试了,但它仍然对用户模型进行分页:在我的控制器中 - $this->modelClass = 'Search'; $this->Crud->execute();
    • 我通过创建一个搜索控制器,然后在那里而不是在用户控制器中调用分页来实现这个工作 - 效果很好。 TY
    猜你喜欢
    • 1970-01-01
    • 2014-06-09
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多