如何将原始sql查询转换为silverstripesqlquery抽象层

mzaanser  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(287)

我有一个页面,我正在试图从数据库中提取与该页面相关的文章。我有一个sql查询,它提取我需要的内容,但是我不断得到错误“where子句中的unknown column'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')
                    ->value();

但是我不知道怎么做。有人能告诉我如何创建一个包含多个连接的sqlquery抽象层吗?
笔记
我使用的是silverstripe版本3.6.1
“fashion”目前是硬编码的,但将被替换为一个我将传入的变量。

kmynzznz

kmynzznz1#

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);

相关问题