慕容的工作随笔

慕容的工作随笔

记录学习和工作

【原创】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);

评论 (0)

还没有评论,来做第一个吧。

发表评论

提交后需管理员审核通过后显示