如何将原始SQL查询转换为Silverstripe SQLQuery抽象层

时间:2018-05-08 16:29:28

标签: php mysql sql join silverstripe

我有一个页面,我正在尝试从数据库中提取与页面相关的文章。我有SQL查询提取我需要但我不断收到错误“'where clause'中的未知列'时尚'”。我相信我需要转换它,

$FilteredStories =  DB::query(' SELECT C.ID, C.URLSegment, C.Title, B.Title AS "Category"
                                FROM `articlepage_categories` AS A
                                JOIN articlecategory AS B ON A.ArticleCategoryID = B.ID
                                JOIN sitetree AS C ON A.ArticlePageID = C.ID
                                WHERE B.Title = "Fashion" LIMIT 5')
                    ->value();

进入SQLQuery抽象层,但我不知道如何。有人可以告诉我如何使用多个连接创建SQLQuery抽象层吗?

备注

  • 我正在使用Silverstripe版本3.6.1
  • “时尚”目前是硬编码的,但将被替换为 我将传入的变量。

1 个答案:

答案 0 :(得分:4)

SilverStripe的数据库默认使用ANSI sql_mode,其中字符串文字需要用单引号括起来。您需要用单引号替换"Fashion"周围的双引号,如下所示:

$FilteredStories =  DB::query('SELECT C.ID, C.URLSegment, C.Title, B.Title AS "Category"
                            FROM `articlepage_categories` AS A
                            JOIN articlecategory AS B ON A.ArticleCategoryID = B.ID
                            JOIN sitetree AS C ON A.ArticlePageID = C.ID
                            WHERE B.Title = \'Fashion\' LIMIT 5')

在此处转义,因为外部引号是单引号。

您的查询将以SQLSelect表示,如此:

$filteredStories = SQLSelect::create();
$filteredStories->selectField('"sitetree"."ID", "sitetree"."URLSegment", "sitetree"."Title", "articlecategory"."Title" AS "Category"');
$filteredStories->setFrom('articlepage_categories');
$filteredStories->addLeftJoin('articlecategory', '"articlecategory"."ID" = "articlepage_categories"."ArticleCategoryID"');
$filteredStories->addLeftJoin('sitetree','"sitetree"."ID" = "articlepage_categories"."ArticlePageID"');
$filteredStories->addWhere('"articlecategory"."Title" = \'Fashion\'');
$filteredStories->setLimit(5);