CakePHP pass custom query from controller into model paginate()

亡梦爱人 提交于 2019-12-11 05:49:10

问题


I am using Cakephp 2.X version

Im going to run sql like:

 SELECT field1, field2, field3, field3,
            ( IF(LOCATE('abc', field1), 4, 0) + IF(LOCATE('abc', field2), 3, 0) + IF(LOCATE('abc', field3), 2, 0) ) AS score
            FROM sometable
            WHERE ( (field1 LIKE '%abc%')  OR  (field2 LIKE '%abc%')  OR  (field3 LIKE '%abc%') )
            ORDER BY score DESC

this sql is generated by code dynamically. So this sql need to be passed into paginate() function in order to do the pagination by cakephp. It seems that cakephp pagination function is not flexible enough to deal with complex sql.

To execute this complex sql, How can I override paginate() to paginate my result?

Description:

I try to do Custom Query Pagination. The Controller get keywords and generate the SQL, I want to pass SQL string to public function paginate(Model $model, $conditions, $fields, $order, $limi ...) function which is overridded in Model to run this custom query. How could i pass SQL string to paginate function.

Any suggestion or hint please?


回答1:


The short answer to your question is that you cannot paginate your data through this query -- or, when using calculated fields altogether. As you have probably noticed, the data, especially in your calculated fields, is not returned to cake in the data->Model->variable array format. Rather, it is returned as an indexed array.

In order to achieve what you are trying to do within the scope of CakePHP, I would use a normal find to get the data that is actually stored in the table and write some Virtual Fields that do the calculations that you are looking for. Then, you can paginate based on the virtual fields:

Since virtual fields behave much like regular fields when doing find’s, Controller::paginate() will be able to sort by virtual fields too.



来源:https://stackoverflow.com/questions/8829373/cakephp-pass-custom-query-from-controller-into-model-paginate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!