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

标签 php mysql sql join silverstripe

我有一个页面,我正在尝试从数据库中提取与该页面相关的文章。我有一个 SQL 查询来提取我需要的内容,但我不断收到错误“‘where 子句’中的未知列‘时尚’”。我相信我需要将其转换为,

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

关于php - 如何将原始 SQL 查询转换为 Silverstripe SQLQuery 抽象层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50238317/

相关文章:

MySQL每小时​​选择平均读数,即使没有读数

sql - SQLite:由两列索引的列的平均值

php - Android 应用程序未与数据库同步

mysql - 如何创建一个触发器,在更新表中的列之前将整个旧行保存到新表中?

php - 如何从选项获取输入,而我必须将数据输入到同一数据库的两个表中,基于选项数据将被插入

php - 是否可以显示这样的表格?

mysql - 标量子查询需要花费大量时间来执行

sql - SQL 数据库设计初学者指南

javascript - 如何更改日期选择器中的语言?

javascript - PHP : Create some form and submit it with <a href