如何在 PhpStorm 中解析带前缀的 SQL table?

How to resolve SQL table with prefix in PhpStorm?

我正在使用 PhpStorm 开发我的 Prestashop 网站,但我无法解决这个问题。我在本地主机上工作并成功将 PhpStorm 连接到我的 MySQL 服务器。

现在 PhpStorm 会抛出类似 "unable to resolve table '${_DB_PREFIX_}cms'" 的警告。 Prestashop 使用 table 名称的前缀,PhpStorm 似乎无法解析那些带有前缀的 tables。

有解决办法吗?

这是 Prestashop-1.6 来源的代码示例:

$sql = 'SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
    FROM `'._DB_PREFIX_.'cms` c
    INNER JOIN `'._DB_PREFIX_.'cms_shop` cs
    ON (c.`id_cms` = cs.`id_cms`)
    INNER JOIN `'._DB_PREFIX_.'cms_lang` cl
    ON (c.`id_cms` = cl.`id_cms`)
    WHERE c.`id_cms_category` = '.(int)$id_cms_category.'
    AND cs.`id_shop` = '.(int)$id_shop.'
    AND cl.`id_lang` = '.(int)$id_lang.
    $where_shop.'
    AND c.`active` = 1
    ORDER BY `position`';

编辑: 在撰写本文时(2016 年),此问题尚无解决方案。但自2018年以来,如, you can now use constants in SQL queries.

所述

其实没有办法处理。但是您可以禁用对此类警告的检查。

  1. 打开 File > Settings > Editor > Inspections
  2. 展开SQL
  3. 取消选中 Unresolved reference

这不起作用的原因是因为您很可能只加载一个架构,您需要加载 information_schema.*

为此,请转到右上角的数据库选项卡,并在其中添加 MySQL 数据库右键单击和 select 属性。

现在您将拥有一个名为 Data Sources and Drivers 的屏幕,它应该在名为 General 的选项卡上打开,单击名为 Schemas 的第三个选项卡并添加 information_schema.*到这个加载模式列表。

单击应用并确定,然后 PhpStorm 现在将了解您的数据库结构,然后能够智能地与您合作,从而消除所有错误。

编辑: 作为mentioned here,这已在 PhpStorm 2018.2 中修复,但仅适用于常量.


我有一个解决方案,不需要将您的 IDE 扔掉。 :) 但是,请注意:这是一个没有保证的丑陋 hack™。

  1. 假设您已经连接到 PhpStorm 中的数据库,为所需的数据库生成 ddl(右键单击连接 -> SQL 脚本 -> 生成 DDL 到剪贴板) :

  2. 将内容粘贴到项目中某处的某个 sql 文件中。你可能应该忽略这个文件。

  3. 将此 ddl 文件中所有表的前缀替换为您的代码中的前缀。使用 PhpStorm 类型提示作为指南。例如 '._DB_PREFIX_.'cms 会变成 ${_DB_PREFIX_}cms:

    请注意,您可能必须使用反引号以避免因花括号而破坏 sql 语法。

  4. 将 ddl 添加到您的 phpstorm 项目中:

  5. 现在一切正常:

$sql 查询上方添加此评论。 /** @noinspection SqlResolve */

这将只抑制这条语句的警告。

对于未来的读者,现在支持: https://www.jetbrains.com/help/phpstorm/2021.1/ide-advanced-metadata.html#set-up-dynamic-prefixes-for-table-names-in-sql-language-injections

.phpstorm.meta.php

<?php

namespace PHPSTORM_META {
override(
// Virtual function to indicate that all SQL
// injections will have the following replacement rules.
sql_injection_subst(),
map([
'{' => "", // all `{` in injected SQL strings will be replaced with a prefix
'}' => '',        // all `}` will be replaced with an empty string
]));
}