Brief introduction of magic methods in ThinkPHP query

  • 2021-07-06 10:14:38
  • OfStack

When we develop with thinkphp, we sometimes use getById ('1') to get the content of a piece of information quickly, which is better than using where ("id = 1")- > find () is much easier to use, and the query efficiency is faster than find.

When people first came into contact with this method, they didn't pay much attention to its internal implementation mechanism, and only thought that they could get information through id, which was not the case.
For example, some systems have methods such as getByTitle ("nihao") and getByMoney ('1000'), which are very similar to getById ('1') mentioned just now, and the functional principle is also similar to getById ('1') 1.
In fact, similar to this getById ($id), getByTitle ($title), getByUserName ($username), etc., the method of "getBy + Field" has a proper noun called "Magic Method", and the fields behind it can be any one field in the data table, and the returned result can only be the first data found out.
Sometimes our fields are not connected, for example: user_name, do we write this (getByUser_name ($name))? The answer is no, this method is not supported in thinkphp. We need to use hump method to name it, which should be written as getByUserName ($name)!


Related articles: