【原创】thinkphp 连接另外一个数据库,及批量更新保存

在config/app.php中添加:

'DB_CONFIG'=>array(
    // 数据库类型
    'type'        => 'mysql',
    // 服务器地址
    'hostname'    => '127.0.0.1',
    // 数据库名
    'database'    => 'test',
    // 数据库用户名
    'username'    => 'root',
    // 数据库密码
    'password'    => 'xxx',
    // 数据库编码默认采用utf8
    'charset'     => 'utf8',
    // 数据库表前缀
    'prefix'      => 'test_',
)

调用:
$db = Db::connect(config('DB_CONFIG'));
$db->name('user')->insert($data);

批量更新需使用模型,在模型中使用另一个数据库的table,需设置:
class Tuser extends Model
{
    protected $connection = array(
        // 数据库类型
        'type'        => 'mysql',
        // 服务器地址
        'hostname'    => '127.0.0.1',
        // 数据库名
        'database'    => 'test',
        // 数据库用户名
        'username'    => 'root',
        // 数据库密码
        'password'    => 'xxx',
        // 数据库编码默认采用utf8
        'charset'     => 'utf8',
        // 数据库表前缀
        'prefix'      => 'test_',
    );
    // 定义主键和数据表
    protected $pk = 'id';
    protected $table = 'test_user';
}
批量更新时:
$userModel = new Tuser();
$userModel->saveAll($data);
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注