Php 如何将原始SQL查询转换为Silverstripe SQLQuery抽象层
我有一个页面,我试图从数据库中提取与该页面相关的文章。我有一个SQL查询,它提取了我需要的内容,但我不断得到错误“where子句”中的“Unknown column'Fashion”。我想我需要把它从Php 如何将原始SQL查询转换为Silverstripe SQLQuery抽象层,php,mysql,sql,join,silverstripe,Php,Mysql,Sql,Join,Silverstripe,我有一个页面,我试图从数据库中提取与该页面相关的文章。我有一个SQL查询,它提取了我需要的内容,但我不断得到错误“where子句”中的“Unknown column'Fashion”。我想我需要把它从 $FilteredStories = DB::query(' SELECT C.ID, C.URLSegment, C.Title, B.Title AS "Category" FROM `articlepage_categorie
$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
- “时尚”目前是硬编码,但将被替换为 我将传入的变量
- SilverStripe的数据库默认使用
ANSI
sql\u模式,其中字符串文本需要用单引号括起来。您需要将“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);