关于 drupal-queries
drupal-queries 是面向 Drupal 开发者的数据库查询参考技能,提供查询构建、数据写入和事务示例,并强调实体查询及参数化 SQL 的使用。
主要功能
- 01构建筛选、排序和联接查询
- 02插入、更新、删除与 upsert
- 03实体查询优先用于实体
- 04注入数据库服务并使用事务
- 05通过参数化查询避免 SQL 拼接
适用场景
- 01查询 Drupal 内容和字段数据
- 02安全地读写自定义数据表
- 03为多步数据库操作添加事务
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-queries安装后在 Claude Code 中输入/drupal-queries确认已加载。
附带文件README.md
详细介绍
Drupal 数据库查询
重要:切勿拼接 SQL
// WRONG — SQL injection risk
$result = $this->database->query("SELECT * FROM {node} WHERE type = '$type'");
// CORRECT — parameterized query
$result = $this->database->query(
"SELECT nid, title FROM {node} WHERE type = :type",
[':type' => $type]
);
Select 查询
$query = $this->database->select('node_field_data', 'n');
$query->fields('n', ['nid', 'title', 'status']);
$query->condition('n.type', 'article');
$query->condition('n.status', 1);
$query->orderBy('n.created', 'DESC');
$query->range(0, 10);
$results = $query->execute()->fetchAll();
// Fetch as associative array
$results = $query->execute()->fetchAllAssoc('nid');
// Fetch single value
$count = $query->countQuery()->execute()->fetchField();
带 Join 的 Select 查询
$query = $this->database->select('node_field_data', 'n');
$query->join('node__field_tags', 'tags', 'n.nid = tags.entity_id');
$query->fields('n', ['nid', 'title']);
$query->condition('tags.field_tags_target_id', $tid);
$query->condition('n.status', 1);
插入
$this->database->insert('my_table')
->fields([
'uid' => $uid,
'data' => serialize($data),
'created' => \Drupal::time()->getRequestTime(),
])
->execute();
Upsert(插入或更新)
$this->database->upsert('my_table')
->key('uid')
->fields(['uid', 'data', 'updated'])
->values([
'uid' => $uid,
'data' => serialize($data),
'updated' => \Drupal::time()->getRequestTime(),
])
->execute();
更新
$this->database->update('my_table')
->fields(['data' => serialize($data)])
->condition('uid', $uid)
->execute();
删除
$this->database->delete('my_table')
->condition('uid', $uid)
->execute();
实体查询(实体优先使用此方式)
// Always prefer EntityQuery over raw SQL for entities
$query = $this->entityTypeManager->getStorage('node')->getQuery()
->accessCheck(TRUE)
->condition('type', 'article')
->condition('status', 1)
->sort('created', 'DESC')
->range(0, 10);
$nids = $query->execute();
注入数据库服务
use Drupal\Core\Database\Connection;
public function __construct(
private readonly Connection $database,
) {}
服务 ID:database
事务
$transaction = $this->database->startTransaction();
try {
$this->database->insert('my_table')->fields([...])->execute();
$this->database->update('other_table')->fields([...])->execute();
}
catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}
// Transaction commits when $transaction goes out of scope
评论
支持 Markdown