Yii2 ActiveQuery循环添加join后返回对象而非预期数组的问题
问题诊断与修复
你的问题出在没有将all()方法的返回值赋值给$logData,这才导致最后输出的还是ActiveQuery对象而非预期的数组。
具体分析
在你的第一段代码中,你是在已有的$logData(ActiveQuery实例)上链式调用all(),但all()方法会执行查询并返回结果数组,而你并没有把这个返回值重新赋值给$logData,所以原变量$logData仍然保持着ActiveQuery对象的引用。
而第二段代码中,你把整个链式调用(包括all())的结果直接赋值给了$logData,自然就能得到数组结果。
修正后的代码
只需要把all()的返回值重新赋值给$logData即可:
$logData = VisitorLog::find() ->select($reportMetaHash[$selectedType]['select']) ->from("visitor_log v"); foreach($reportMetaHash[$selectedType]['joins'] as $join){ $logData->join($join['type'],$join['table'],$join['on']); } // 关键:将all()的返回值赋值给$logData $logData = $logData->where(['=', 'v.app_id' , $app_id]) ->andWhere(['=', 'assorted_id' , $selectedType]) ->andWhere(['>=', 'access_time', $app->start_date]) ->andWhere('assorted_id IN ('.$selectedType.')') ->groupBy("v.access_log_id, v.content_id") ->orderBy('b.booth_name, u.`first_name`') ->asArray() ->all(); echo '<pre>'; print_r($logData); exit;
额外注意事项
- 你的查询中存在重复条件:
andWhere(['=', 'assorted_id' , $selectedType])和andWhere('assorted_id IN ('.$selectedType.')'),这两个逻辑重复,建议保留一个即可。如果$selectedType是多个值,第一个条件会导致查询结果不符合预期,建议统一使用IN的写法,并且最好用参数绑定避免SQL注入:->andWhere(['assorted_id' => is_array($selectedType) ? $selectedType : [$selectedType]]) - 循环中的
join调用是没问题的,Yii2的ActiveQuery方法都是链式返回$this,所以循环中修改$logData的操作是有效的,这部分逻辑本身没有错误。
内容的提问来源于stack exchange,提问作者xmaestro
相关产品推荐
相关产品推荐

