【问题标题】:Select distinct results, when using with() operator in Yii在 Yii 中使用 with() 运算符时选择不同的结果
【发布时间】:2014-04-25 14:50:57
【问题描述】:

在 Yii 中使用 with() 运算符时,如何从关系表中仅选择不同的记录?

我的模型(记录)是这样的:

$probe = Probes::model()->with(array
(
    'user',
    'results',
    'results.answer',
    'survey',
    'survey.questions',
    'survey.questions.question',
    'survey.questions.question.answers',
    'manager'
))->findByPk($id);

我想确保survey.questions 关系只返回不同的记录。但似乎,我没有看到任何方法来实现这一点(或者我是盲人/没有受过足够的教育)。

将关系表名/别名作为数组给出时:

'results.question'=>array('alias'=>'results_question'),

the distinct key is not among those, that can be used in such array (as modifier).

我尝试了将select 从默认* 更改为DISTINCT * 的非常丑陋、颠簸的方式:

'survey.questions'=>array('select'=>'distinct'),

但这(当然?)失败了:

Active record "SurveysQuestions" is trying to select an invalid column "distinct". Note, the column must exist in the table or be an expression with alias.

如果有可能(使用with()),我怎样才能实现这一点(看起来如此明显和容易)?如果没有,那么 - 请建议如何以任何方式获取关系表中的不同记录(除了使用 foreach 手动过滤结果,我现在正在做什么,以及什么是丑陋的)。 p>

【问题讨论】:

  • 似乎查询生成器将不同的列视为一列。尝试在它后面指定字段:array('select' => 'distinct id, ..., ..., etc')
  • @AndreyMischenko 不,没有变化(我并不感到惊讶)。这次Active record "SurveysQuestions" is trying to select an invalid column "distinct *"Active record "SurveysQuestions" is trying to select an invalid column "distinct id" 等等! :[

标签: activerecord distinct yii


【解决方案1】:

您可以将 CDbCriteria::distinct 设置为 true:

'survey.questions'=>array('distinct'=>true),

【讨论】:

  • 我接受你的回答,它确实回答了我的问题。但是,我犯了同样的错误,就像this guy。从an answer 到他的问题,我发现我把DISTINCT 误认为GROUP BY。知道了这一点,我设法解决了我的问题。不幸的是,基于自动生成的别名,这不是适合我的东西。所以...也许你可以帮忙 -> here.
猜你喜欢
  • 1970-01-01
  • 2021-12-16
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 2021-01-26
  • 2014-03-21
相关资源
最近更新 更多