thinkphp中的getbyEmail等getby方法

ThinkPHP getBy动态查询是一个魔术方法,可以根据某个字段名称动态得到对应的一条数据记录。

这个方法定义在thinkphplibrary hinkdbQuery.php文件中。

当我们在定义一个模型类的时候会引用到thinkModel(.php)而thinkModel.php中引用了thinkdbQuery(.php)

<?php
 namespace appindexmodel;
 use thinkModel;
 
 class User extends Model
 {
 }

这个魔术方法定义如下:

    public function __call($method, $args)
    {
        if (strtolower(substr($method, 0, 5)) == 'getby') {
            // 根据某个字段获取记录
            $field         = Loader::parseName(substr($method, 5));
            $where[$field] = $args[0];
            return $this->where($where)->find();
        } elseif (strtolower(substr($method, 0, 10)) == 'getfieldby') {
            // 根据某个字段获取记录的某个值
            $name         = Loader::parseName(substr($method, 10));
            $where[$name] = $args[0];
            return $this->where($where)->value($args[1]);
        } else {
            throw new Exception('method not exist:' . __CLASS__ . '->' . $method);
        }
    }

由这个方法定义可以看出,这个方法会读取被调用的方法前五个字符是不是getby,如果是getby,就会拿方法中的getby后面的字符串去匹配数据库中的一个字段,

从而通过where查询的方式来获取数据库中这个字段对应的那条数据并返回

原文地址:https://www.cnblogs.com/flyfish919/p/6875137.html