illuminate/database 使用 四

2023-11-27 11:15
文章标签 使用 database illuminate

本文主要是介绍illuminate/database 使用 四,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文档:Hyperf

Database: Getting Started - Laravel 10.x - The PHP Framework For Web Artisans

因为hyperf使用illuminate/database,所以按照文章,看illuminate/database代码实现。

一、读写分离

根据文档读写的host可以分开。设置读写分离的前提,做数据库出从同步。
 

1.1 数据库主从同步

参考:mysql5.7 主从配置-CSDN博客

1.2 设置

配置中设置三个数据read、write、sticky。read、write都包含host数组,其配置会和主要配置合并。就是说,比如host相同,应该在read、write中设置对应数据,以覆盖主要设置。

sticky选项是一个可选值,可用于允许在当前请求周期内立即读取已写入数据库的记录。如果启用了sticky选项,并且在当前请求周期中对数据库执行了“写”操作,则任何进一步的“读”操作都将使用“写”连接。这确保了在请求周期内写入的任何数据都可以在同一请求期间立即从数据库中读回。

源码如下:

#Illuminate\Database\Connectors\ConnectionFactory
protected function getReadConfig(array $config){return $this->mergeReadWriteConfig($config, $this->getReadWriteConfig($config, 'read'));}
protected function getWriteConfig(array $config){return $this->mergeReadWriteConfig($config, $this->getReadWriteConfig($config, 'write'));}
protected function mergeReadWriteConfig(array $config, array $merge){return Arr::except(array_merge($config, $merge), ['read', 'write']);}#Illuminate\Database\Connection
public function getReadPdo(){if ($this->transactions > 0) {return $this->getPdo();}if ($this->readOnWriteConnection ||($this->recordsModified && $this->getConfig('sticky'))) {return $this->getPdo();}if ($this->readPdo instanceof Closure) {return $this->readPdo = call_user_func($this->readPdo);}return $this->readPdo ?: $this->getPdo();}

1.3 测试

配置如下

#config/database.php
return ['migrations' => '', //数据迁移//PDO文档 https://www.php.net/manual/zh/pdo.constants.php'default' => 'master','connections' => ['master' => ['driver' => 'mysql','host' => 'localhost','database' => 'test','username' => 'root','password' => 'qwe110110','charset' => 'utf8','collation' => 'utf8_general_ci','prefix' => '','port' => '3306','read' => ['host' => ['127.0.0.1'],'port' => '3307',],'write' => ['host' => ['127.0.0.1'],'port' => '3306',],],]
];

 测试代码

function test1()
{new App();$query = "concat('-',id)";$as = "id";//$info1 = DbManager::table('userinfo')->select(['name'])->selectSub($query, $as)->addSelect(['age'])->get();$info1 = DbManager::table('userinfo')->select(['name'])->selectSub($query, $as)->addSelect(['age'])->get();var_dump($info1);$data = $info1->all();$insertData = ['name' => 'test1', 'age' => 1];$id = DbManager::table('userinfo')->insertGetId($insertData);var_dump($id);//exit;//$sql = "CONCAT('A-',name)";//$info2 = DbManager::table('userinfo')->selectSub($sql, "table")->toSql()->dump();
}
test1();

 返回结果

string(29) "Illuminate\Support\Collection"
array(8) {[0] =>class stdClass#18 (3) {public $name =>string(3) "123"public $id =>string(2) "-1"public $age =>int(22)}[1] =>class stdClass#22 (3) {public $name =>string(5) "name2"public $id =>string(2) "-2"public $age =>int(13)}[2] =>class stdClass#23 (3) {public $name =>string(5) "name3"public $id =>string(2) "-3"public $age =>int(24)}[3] =>class stdClass#24 (3) {public $name =>string(5) "33321"public $id =>string(2) "-4"public $age =>int(0)}[4] =>class stdClass#25 (3) {public $name =>string(5) "test1"public $id =>string(2) "-5"public $age =>int(1)}[5] =>class stdClass#26 (3) {public $name =>string(5) "test1"public $id =>string(2) "-6"public $age =>int(1)}[6] =>class stdClass#27 (3) {public $name =>string(5) "test1"public $id =>string(2) "-7"public $age =>int(1)}[7] =>class stdClass#28 (3) {public $name =>string(5) "test1"public $id =>string(2) "-8"public $age =>int(1)}
}
int(9)

 从库:

 主库

 

 测试成功~

1.4 返回数据处理

从测试结果看,返回的都是对象,因为默认使用PDO::FETCH_OBJ。

参考:PHP: PDO - Manual

源码如下

#Illuminate\Database\Capsule\Manager
public function __construct(Container $container = null){$this->setupContainer($container ?: new Container);// Once we have the container setup, we will setup the default configuration// options in the container "config" binding. This will make the database// manager work correctly out of the box without extreme configuration.$this->setupDefaultConfiguration();$this->setupManager();}
protected function setupDefaultConfiguration(){$this->container['config']['database.fetch'] = PDO::FETCH_OBJ;$this->container['config']['database.default'] = 'default';}
public function setFetchMode($fetchMode){$this->container['config']['database.fetch'] = $fetchMode;return $this;}#Illuminate\Database\Connection
protected $fetchMode = PDO::FETCH_OBJ;
public function select($query, $bindings = [], $useReadPdo = true){return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {if ($this->pretending()) {return [];}// For select statements, we'll simply execute the query and return an array// of the database result set. Each element in the array will be a single// row from the database table, and will either be an array or objects.$statement = $this->prepared($this->getPdoForSelect($useReadPdo)->prepare($query));$this->bindValues($statement, $this->prepareBindings($bindings));$statement->execute();return $statement->fetchAll();});}
protected function prepared(PDOStatement $statement){$statement->setFetchMode($this->fetchMode);$this->event(new StatementPrepared($this, $statement));return $statement;}

想返回数组可以设置为PDO::FETCH_ASSOC。最简单的方法就是替换源码,二次开发最好就是用对象,或者写个对象转数组的方法,tp里面有源码。tp是查出来对象,可使用toArray()搞成数组。

get()返回的类是Illuminate\Support\Collection,此类中还有一些数据统计的方法,比如平均值之类。意思就是查出来数据再做数据统计。

二、多库配置

根据laravel文档:如果应用程序在config/database.php配置文件中定义了多个连接,则可以通过DB facade提供的连接方法访问每个连接。

use Illuminate\Support\Facades\DB;$users = DB::connection('sqlite')->select(/* ... */);
$pdo = DB::connection()->getPdo();

但是仅用这个库由于没有对应数据,会返回db类是null。

源码如下:

#Illuminate\Support\Facades\Facade
public static function getFacadeRoot(){return static::resolveFacadeInstance(static::getFacadeAccessor());}
public static function __callStatic($method, $args){$instance = static::getFacadeRoot();if (!$instance) {throw new RuntimeException('A facade root has not been set.');}return $instance->$method(...$args);}protected static function resolveFacadeInstance($name){if (is_object($name)) {return $name;}if (isset(static::$resolvedInstance[$name])) {return static::$resolvedInstance[$name];}if (static::$app) {return static::$resolvedInstance[$name] = static::$app[$name];}}

根据方法resolveFacadeInstance(),$name应该是‘db’,不是对象,$resolvedInstance、$app没有对应对象,所以返回空。估计得配合其他类库。比如hyperf中需要

composer require hyperf/database

 那么不用其他类库怎么实现多库切换……

多库配置

return ['migrations' => '', //数据迁移//PDO文档 https://www.php.net/manual/zh/pdo.constants.php'default' => 'master','connections' => ['master' => ['driver' => 'mysql','host' => 'localhost','database' => 'test','username' => 'root','password' => 'mima','charset' => 'utf8','collation' => 'utf8_general_ci','prefix' => '','port' => '3306','read' => ['host' => ['127.0.0.1'],'port' => '3307',],'write' => ['host' => ['127.0.0.1'],'port' => '3306',],],'test' => ["driver" => "mysql","host" => "127.0.0.1","database" => "test1","username" => "root","password" => "mima",'charset' => 'utf8mb4','collation' => 'utf8mb4_unicode_ci','prefix' => '','port' => '3307',],],
];
function test2()
{$app = new App();$info = DbManager::connection('test')->table('userinfo')->where('id', '=', 1)->get();$info = $info->first();var_dump($info);
}test2();

 返回数据

class stdClass#20 (2) {public $id =>int(1)public $name =>string(1) "1"
}

这篇关于illuminate/database 使用 四的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/427554

相关文章

Spring @RequestMapping 注解及使用技巧详解

《Spring@RequestMapping注解及使用技巧详解》@RequestMapping是SpringMVC中定义请求映射规则的核心注解,用于将HTTP请求映射到Controller处理方法... 目录一、核心作用二、关键参数说明三、快捷组合注解四、动态路径参数(@PathVariable)五、匹配请

Java 枚举的基本使用方法及实际使用场景

《Java枚举的基本使用方法及实际使用场景》枚举是Java中一种特殊的类,用于定义一组固定的常量,枚举类型提供了更好的类型安全性和可读性,适用于需要定义一组有限且固定的值的场景,本文给大家介绍Jav... 目录一、什么是枚举?二、枚举的基本使用方法定义枚举三、实际使用场景代替常量状态机四、更多用法1.实现接

springboot项目中使用JOSN解析库的方法

《springboot项目中使用JOSN解析库的方法》JSON,全程是JavaScriptObjectNotation,是一种轻量级的数据交换格式,本文给大家介绍springboot项目中使用JOSN... 目录一、jsON解析简介二、Spring Boot项目中使用JSON解析1、pom.XML文件引入依

Java中的record使用详解

《Java中的record使用详解》record是Java14引入的一种新语法(在Java16中成为正式功能),用于定义不可变的数据类,这篇文章给大家介绍Java中的record相关知识,感兴趣的朋友... 目录1. 什么是 record?2. 基本语法3. record 的核心特性4. 使用场景5. 自定

如何解决Druid线程池Cause:java.sql.SQLRecoverableException:IO错误:Socket read timed out的问题

《如何解决Druid线程池Cause:java.sql.SQLRecoverableException:IO错误:Socketreadtimedout的问题》:本文主要介绍解决Druid线程... 目录异常信息触发场景找到版本发布更新的说明从版本更新信息可以看到该默认逻辑已经去除总结异常信息触发场景复

MyBatis编写嵌套子查询的动态SQL实践详解

《MyBatis编写嵌套子查询的动态SQL实践详解》在Java生态中,MyBatis作为一款优秀的ORM框架,广泛应用于数据库操作,本文将深入探讨如何在MyBatis中编写嵌套子查询的动态SQL,并结... 目录一、Myhttp://www.chinasem.cnBATis动态SQL的核心优势1. 灵活性与可

Python使用Tkinter打造一个完整的桌面应用

《Python使用Tkinter打造一个完整的桌面应用》在Python生态中,Tkinter就像一把瑞士军刀,它没有花哨的特效,却能快速搭建出实用的图形界面,作为Python自带的标准库,无需安装即可... 目录一、界面搭建:像搭积木一样组合控件二、菜单系统:给应用装上“控制中枢”三、事件驱动:让界面“活”

C/C++ chrono简单使用场景示例详解

《C/C++chrono简单使用场景示例详解》:本文主要介绍C/C++chrono简单使用场景示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友... 目录chrono使用场景举例1 输出格式化字符串chrono使用场景China编程举例1 输出格式化字符串示

MySQL 表的内外连接案例详解

《MySQL表的内外连接案例详解》本文给大家介绍MySQL表的内外连接,结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录表的内外连接(重点)内连接外连接表的内外连接(重点)内连接内连接实际上就是利用where子句对两种表形成的笛卡儿积进行筛选,我

Python验证码识别方式(使用pytesseract库)

《Python验证码识别方式(使用pytesseract库)》:本文主要介绍Python验证码识别方式(使用pytesseract库),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全... 目录1、安装Tesseract-OCR2、在python中使用3、本地图片识别4、结合playwrigh