[ // 数据库类型 "type" => "mysql", // 服务器地址 "hostname" => "127.0.0.1", // 数据库名 "data" />
入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

ThinkPHP5多个数据库查询注意项

创建时间:2018-07-13 投稿人: 浏览次数:902
  1. 数据库切换
    i. 在config.php中添加数据库配置数组
//数据库配置1
"db_config1" => [
// 数据库类型
"type" => "mysql",
// 服务器地址
"hostname" => "127.0.0.1",
// 数据库名
"database" => "thinkphp",
// 数据库用户名
"username" => "root",
// 数据库密码
"password" => "",
// 数据库编码默认采用utf8
"charset" => "utf8",
// 数据库表前缀
"prefix" => "think_",
],
//数据库配置2
"db_config2" => "mysql://root:1234@localhost:3306/thinkphp#utf8";

将查询语句改成(这里要用‘->’连接table()方法;之前是‘::’)

Db::connect("db_config1")->table("test1")->field("*")->select();
Db::connect("db_config2")->table("test1")->field("*")->select();
  1. 将特定的SQL语句修改为TP5的链式操作
    原SQL语句如下:
SELECT parent.name, COUNT(product.name)
FROM nested_category AS node,
nested_category AS parent,
product
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.category_id = product.category_id
GROUP BY parent.name
ORDER BY node.lft

使用默认的数据库配置时

$res = Db::table("nested_category node,nested_category parent,product")
            ->field("parent.name,count(product.name)")
            ->where("node.category_id","exp", "= product.category_id")
            ->where("node.lft","exp", "between parent.lft and parent.rgt")
            ->group("parent.name")
            ->order("node.lft")
            ->select();

使用第二个数据库配置时(table()前用‘->’连接;且多个数据库名用‘[]’包围,转为数组)

$testConnect = Db::connect("test_conf");
$res = $testConnect->table(["nested_category node,nested_category parent,product"])
            ->field("parent.name,count(product.name)")
            ->where("node.category_id","exp", "= product.category_id")
            ->where("node.lft","exp", "between parent.lft and parent.rgt")
            ->group("parent.name")
            ->order("node.lft")
            ->select();
阅读更多
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像