普通网友 2014-03-18 14:21
浏览 45
已采纳

在cakephp中限制mysql调用相同的信息

I'm using cakephp but this could potentially apply to any framework / php-based environment.

I have a blogging platform and people can like, share, comment etc. Each of these likes, shares and comments have an associated user and this means that the same user is requested from the database many many times for different things, running this same query:

SELECT `User`.`id`, `User`.`username`, `User`.`fullname`, `User`.`avatar`, FROM `db`.`users` AS `User` WHERE `User`.`id` = 127

Is there a way that I can stop this from happening, apart from caching? Or does it not really matter that MySQL is doing the same call 5 or more times for the same information?

Thanks

  • 写回答

2条回答 默认 最新

  • doulai2573 2014-03-20 01:19
    关注

    It's CAKE way - to get many simple queries and cache them.

    Check Your all $this->YourModelName->find() queries - probably You do not use recursive or contain options, so when You take comments data, CAKE takes related models too (hasMany/belongsTo relations in Your models). You can:

    • use $this->loadModel(YourModelName); to load model on the fly
    • use $this->YourModelName->Behaviors->attach('Containable'); to attach selected models and fields
    • set recursive => -1 to get data from one model/table only
    • use own query with join option (it can be one query instead of contain or recursive option)
    • for some data like User data You can storage it in session like $this->Session->write()
    • if You use Auth component, You can get from auth like $this->Auth->user('id')
    • always You can set for all models $useTable = false and link models on the fly but it's not efficient/economic way (especially when You have to manage Your project in further time)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?