Drupal8 数据库查询
单条数据查询
$database = \Drupal::database();
$query = $database->select('users_field_data', 'u');
$query->fields('u', ['uid', 'name', 'status', 'created', 'access']);
$result=$query->execute()->fetch();
多条数据查询
$database = \Drupal::database();
$query = $database->select('users_field_data', 'u');
$query->fields('u', ['uid', 'name', 'status', 'created', 'access']);
$query->range(0, 50);
$list=$query->execute()->fetchAll();
插入
$result = \Drupal::database()->insert('mytable')->fields([])->execute();
修改
$rea=\Drupal::database()->update('mytable')->fields([])->condition()->execute();
删除
$res = \Drupal::database()->delete('mytable')->condition('myfield', 5)->execute();
总数查询
$number_of_rows = \Drupal::database()->select('mytable')->countQuery()->execute()->fetchField();
数据回滚
$transaction = $connection->startTransaction();
try {
}catch (Exception $e) {
$transaction->rollBack();
}
$transaction->commit();
缓存调用
echo '<pre>';
$cache=\Drupal::cache();
$cache_dta=$cache->get('aaa');
if(!$cache_dta){
echo '---1--';
$cache->set('aaa',[1,2,3],time()+60);
}
echo '---2--';
var_dump($cache_dta);
exit;
分页
$database = \Drupal::database();
$query = $database->select('user', 'p');
//总条数
$total=$query->countQuery()->execute()->fetchField();;
// 每页数量
$num_per_page =50;
$pager = $query->orderBy('p.create_time','desc')->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit($num_per_page);
$list = $pager->execute()->fetchAll();
$pager = \Drupal::service('pager.manager')->createPager($total, $num_per_page);
//获取当前页码
$page = $pager->getCurrentPage();
$pager = \Drupal::service('pager.manager')->createPager(50, 2);
//获取当前页码
$page = $pager->getCurrentPage();
$offset = $num_per_page * $page;
$render = [];
$render[] = [
'#theme' => 'prize_export',
'#data' => $list,
];
// Finally, add the pager to the render array, and return.
$render[] = ['#type' => 'pager'];
return $render;