数据库操作


在控制器通过db获得数据库实例,使用ORM会给带来一些性能的损耗,所以使用编写SQL+使用PDO进行数据库的操作是最好的了,只需编写原生SQL.

增删查改的具体方法:

  • 在控制器中使用

继承父类Controller后,我们可以使用

    $this->>db()
  • 在model分层中使用

在app/models中编写你的model,继承父类Models,我们就可以使用

    $this->db()

具体可以见app/Models/User文件

上述两种方法可以获取到数据库连接对象

  • 插入数据以及获取插入的ID
$insertId = $this->>db()->table('profile')->insertGetId([
    'name'      => 'test-name',
    'gender'    => 1,
    'birthday'  => '1988-12-01 01:00:01', //DATETIME
    'memo'      => 'this is a test memo',
    'lat'       => '30.54916000', //DECIMAL(10,8)
    'lng'       => '104.06761000' //DECIMAL(11,8)
]);
  • 插入数据以及获取影响的行数
$affectNum =  $this->>db()->table('profile')->insert([
    [
        'name'      => 'test-name',
        'gender'    => 1,
        'birthday'  => '1988-12-01 01:00:01',
        'memo'      => 'this is a test memo',
        'lat'       => '30.54916000',
        'lng'       => '104.06761000'
    ],
    [
        'name'      => 'test-name-1',
        'gender'    => 1,
        'birthday'  => '2010-12-01 01:00:01',
        'memo'      => 'this is another test memo',
        'lat'       => '30.54916000',
        'lng'       => '104.06761000'
    ],
]);
  • 更新数据并获得影响的行数
affectNum = $this->>db()->update('update profile set name = :name, memo = :memo where id = :id', [
    ':name'     => 'test-name',
    ':memo'     => 'this is another memo',
    ':id'       => $id,
]);
  • 查询
$records = $this->>db()->select('select * from profile where id = :id', [
    ':id'   => $id,
]);
  • 删除并获得影响的行数
$affectNum = $this->>db()->delete('delete from profile where id = :id', [
    ':id'       => $id,
]);
  • 事务
$conn->transaction(function ($conn) {
    //do something...
});
  • 获取查询日志
$queryLogs = $this->>db()->getQueryLog();