在tp6中,你还在用常用的链式方式操作数据库吗?下面介绍一种非主流的链式操作,保证让你的代码与别人与众不同。
在tp6的核心文件BaseQuery.php
中给我们装载了一个call方法,如图上代码:
/**
* 利用__call方法实现一些特殊的Model方法
* @access public
* @param string $method 方法名称
* @param array $args 调用参数
* @return mixed
* @throws Exception
*/
public function __call(string $method, array $args)
{
if (strtolower(substr($method, 0, 5)) == 'getby') {
// 根据某个字段获取记录
$field = Str::snake(substr($method, 5));
return $this->where($field, '=', $args[0])->find();
} elseif (strtolower(substr($method, 0, 10)) == 'getfieldby') {
// 根据某个字段获取记录的某个值
$name = Str::snake(substr($method, 10));
return $this->where($name, '=', $args[0])->value($args[1]);
} elseif (strtolower(substr($method, 0, 7)) == 'whereor') {
$name = Str::snake(substr($method, 7));
array_unshift($args, $name);
return call_user_func_array([$this, 'whereOr'], $args);
} elseif (strtolower(substr($method,