Mixed query of tp5+Mongodb and Mysql database
Preface
MongoDB mass data query is fast without data model
Suitable for log database
Or the intermediate database reads and stores some business data to be read from the MySQL database
MongoDB is not suitable for multi table transaction function, and there is not a good determination mechanism for write operation. It is not suitable for being a database of business data
Reading and writing business data transactions stored in MySQl
Implementation process
Configure database
<?php
return [
'type' => '\think\mongo\Connection',
'hostname' => 'localhost',
'database' => 'tuzi',
'username' => '',
'password' => '',
'hostport' => '27017',
'dsn' => '',
'params' => [],
'charset' => 'utf8',
'prefix' => '',
];
Configure config
'mysql_db' => [
'type' => 'mysql',
'hostname' => 'localhost',
'database' => 'tuzi',
'username' => 'root',
'password' => '111',
'hostport' => '',
'dsn' => '',
'params' => [],
'charset' => 'utf8',
'prefix' => '',
'debug' => true,
'deploy' => 0,
'rw_separate' => false,
'master_num' => 1,
'slave_no' => '',
'fields_strict' => true,
'resultset_type' => 'array',
'auto_timestamp' => false,
'datetime_format' => 'Y-m-d H:i:s',
'sql_explain' => false,
]
code implementation
<?php
namespace app\index\controller;
use think\Db;
class Index
{
public function index()
{
echo "--------I passed mongodb Queried data----------<br/>";
$data = array('a'=>'Element 1','b'=>'Element 2');
$res = Db::table('document')->select();
dump($res);
echo "--------I passed mysql Queried data----------<br/>";
$res1 = Db::connect(Config('mysql_db'))->table('admin')->select();
dump($res1);
return "Completed successfully";
}
}
Operation results
--------I passed mongodb Queried data----------
array(3) {
[0] => array(3) {
["_id"] => object(MongoDB\BSON\ObjectId)
["oid"] => string(24) "5a51bf6583869e4b62321af3"
}
["a"] => string(7) "Element 1"
["b"] => string(7) "Element 2"
}
[1] => array(3) {
["_id"] => object(MongoDB\BSON\ObjectId)
["oid"] => string(24) "5a51bfa083869e4b647a61c6"
}
["a"] => string(7) "Element 1"
["b"] => string(7) "Element 2"
}
[2] => array(3) {
["_id"] => object(MongoDB\BSON\ObjectId)
["oid"] => string(24) "5a51c30383869e4b674156f6"
}
["a"] => string(7) "Element 1"
["b"] => string(7) "Element 2"
}
}
--------I passed mysql Queried data----------
array(1) {
[0] => array(3) {
["admin_id"] => int(1)
["user_name"] => string(5) "admin"
["password"] => string(3) "888"
}
}
//Completed successfully 0.030056s ShowPageTrace
Keywords:
Database
MongoDB
MySQL
PHP
Added by steved on Tue, 05 May 2020 01:46:33 +0300