Home  >  Article  >  Backend Development  >  ThinkPHP查询中的魔术方法简述_php实例

ThinkPHP查询中的魔术方法简述_php实例

WBOY
WBOYOriginal
2016-06-07 17:18:04704browse

我们在使用thinkphp开发的时候,有时候会用到getById('1')这个方法快速的获取一条信息的内容,这个方法比用where(" id =1 ")->find()好用多了,同时查询效率也比find快速。

很多人在刚开始接触这个方法的时候,没有多留意它的内部实现机制,仅仅认为是通过id来获取信息,而事实并非如此。
例如有的系统里存在getByTitle("nihao")、getByMoney('1000')这类方法,这些与刚才提到的getById('1')很相似,同时实现的功能原理也与getById('1')一样。
其实类似这种getById($id)、getByTitle($title)、getByUserName($username)等等,以“getBy+字段”的方法有个专有名词叫做“魔术方法”它后面的字段可以是数据表中的任何一个字段,返回结果只能是查询出来的第一条数据,这种方法查询的效率很高,很好记住。
有时候我们的字段不是连起来的,例如:user_name 这样子的字段,我们是不是这样子写(getByUser_name($name))呢?答案是否定的,thinkphp中不支持这样子的方法,我们需要使用驼峰法来命名,应该写成这样 getByUserName($name)就可以了!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn