<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\db;
use PDO;
use think\Cache;
use think\Collection;
use think\Config;
use think\Db;
use think\db\Builder;
use think\db\Connection;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Loader;
use think\Model;
use think\model\Relation;
use think\Paginator;
class Query
{
// 数据库Connection对象实例
protected $connection;
// 数据库驱动类型
protected $builder;
// 当前模型类名称
protected $model;
// 当前数据表名称(含前缀)
protected $table = '';
// 当前数据表名称(不含前缀)
protected $name = '';
// 当前数据表主键
protected $pk;
// 当前数据表前缀
protected $prefix = '';
// 查询参数
protected $options = [];
// 参数绑定
protected $bind = [];
// 数据表信息
protected static $info = [];
/**
* 架构函数
* @access public
* @param Connection $connection 数据库对象实例
* @param string $model 模型名
*/
public function __construct(Connection $connection = null, $model = '')
{
$this->connection = $connection ?: Db::connect([], true);
$this->builder = $this->connection->getConfig('builder') ?: $this->connection->getConfig('type');
$this->prefix = $this->connection->getConfig('prefix');
$this->model = $model;
}
/**
* 利用__call方法实现一些特殊的Model方法
* @access public
* @param string $method 方法名称
* @param array $args 调用参数
* @return mixed
* @throws DbException
* @throws Exception
*/
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);
}
}