Silverstripe SQL 逻辑
Silverstripe SQL Logic
我正在尝试 运行 查询,但发生了一些奇怪的事情:
$return = MyCustomPage::get()->where(
" MyCustomPage.ID IN(" . implode(',', $MyCustomPageIds) . ")"
)->limit(2);
这是一个 return 错误,因为查询试图从 MyCustomPage_Live 而不是 MyCustomPage 获取数据.
这个逻辑一直在变化,有时它来自一个 table 有时来自另一个,我需要在查询中指定 table 名称(例如 MyCustomPage.ID 或 MyCustomPage_Live.ID )
是否有更好的方法或任何解决方案?
您应该尽量避免原始 SQL 查询,而应利用 SilverStripe ORM。
因此,为了实现与 where 语句相同的效果,但是通过使用 ORM,您将编写:
$return = MyCustomPage::get()->byIDs($MyCustomPageIds)->limit(2);
这也会自动从当前阶段读取。如果你需要强制读取一个阶段,你可以使用类似的东西:
// replace 'Live' with 'Stage' to read from stage.
Versioned::set_stage('Live');
在这些情况下,最好先存储当前阶段,然后再恢复它。
$currentStage = Versioned::get_stage();
Versioned::set_stage('Live');
// Do your thing…
Versioned::set_stage($currentStage);
您不需要 where
语句来执行此操作,您可以按照 CustomPage::get()->filter(['ID' => $CustomPageArray])->limit(2)
的方式做一些事情。数组作为 SilverStripe 中的第二个参数被视为 IN
类型的查询。使用 filter
也将自动解决版本控制问题,这正是您 运行 所面临的问题。
如果你真的需要使用 where
,像这样的东西会有所帮助:
$extra = '';
if (Versioned::current_stage() == 'Live') {
$extra = '_live'
}
Page::get()->where('MyFilter' . $extra . '.ID' IN implode(',', $CustomIds));
在此处输入代码
(请原谅任何语法错误;))
我正在尝试 运行 查询,但发生了一些奇怪的事情:
$return = MyCustomPage::get()->where(
" MyCustomPage.ID IN(" . implode(',', $MyCustomPageIds) . ")"
)->limit(2);
这是一个 return 错误,因为查询试图从 MyCustomPage_Live 而不是 MyCustomPage 获取数据.
这个逻辑一直在变化,有时它来自一个 table 有时来自另一个,我需要在查询中指定 table 名称(例如 MyCustomPage.ID 或 MyCustomPage_Live.ID )
是否有更好的方法或任何解决方案?
您应该尽量避免原始 SQL 查询,而应利用 SilverStripe ORM。
因此,为了实现与 where 语句相同的效果,但是通过使用 ORM,您将编写:
$return = MyCustomPage::get()->byIDs($MyCustomPageIds)->limit(2);
这也会自动从当前阶段读取。如果你需要强制读取一个阶段,你可以使用类似的东西:
// replace 'Live' with 'Stage' to read from stage.
Versioned::set_stage('Live');
在这些情况下,最好先存储当前阶段,然后再恢复它。
$currentStage = Versioned::get_stage();
Versioned::set_stage('Live');
// Do your thing…
Versioned::set_stage($currentStage);
您不需要 where
语句来执行此操作,您可以按照 CustomPage::get()->filter(['ID' => $CustomPageArray])->limit(2)
的方式做一些事情。数组作为 SilverStripe 中的第二个参数被视为 IN
类型的查询。使用 filter
也将自动解决版本控制问题,这正是您 运行 所面临的问题。
如果你真的需要使用 where
,像这样的东西会有所帮助:
$extra = '';
if (Versioned::current_stage() == 'Live') {
$extra = '_live'
}
Page::get()->where('MyFilter' . $extra . '.ID' IN implode(',', $CustomIds));
在此处输入代码
(请原谅任何语法错误;))