Yii 按类型获取记录
我想知道 Yii 是否有一种有效的方法来按类型对项目进行分组。
假设我有以下模型:
Tag
------
id
name
type_id
假设有 5 种不同类型的 Tag
。我希望能够在索引中按 type_id
显示部分中的所有标签。有没有 Yii 的方式来实现这个?
在框架之外,我会编写一个函数,从数据库获取的结果存储如下:
$tags[$typeID][] = $tag;
然后在每个部分我可以做类似的事情:
foreach( $tags[$typeID] as $tag )
{
// Here are all tags for one $typeID
}
但是我很难弄清楚如何在 Yii 中执行此操作,而不需要:
A)循环首先读取整个结果集并重写它,或者,
B) 运行 5 个不同的查询。
I'm wondering if Yii has an efficient method for grouping items by type.
Let's say I have the following model:
Tag
------
id
name
type_id
And let's say there are 5 different types of Tag
s. I want to be able to display in my index all tags in sections by type_id
. Is there a Yii-way of accomplishing this?
Outside a framework I would write a function such that results fetched from the DB were stored like this:
$tags[$typeID][] = $tag;
Then in each section I could do something like:
foreach( $tags[$typeID] as $tag )
{
// Here are all tags for one $typeID
}
But I'm having difficulty figuring out how to do this in Yii without:
A) looping through the entire result set first and rewriting it or,
B) running 5 different queries.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 ActiveRecord 时,只需在 DBCriteria 中指定“索引”即可。因此,在查询中执行以下操作:
这将返回您之后的关联数组。 TBF 它可能执行完全相同的代码,但这显然比在任何地方执行它更容易使用。
When using ActiveRecord simply specify the "index" in the DBCriteria. So in a query do:
That will return an assoc array that your after. TBF it probably executes exactly the same code, but this is obviously easier to use that performing it everywhere.
假设您的活动记录类名为
MyActiveRecordClass
,最简单的方法应该就足够了:如果您提供有关如何显示分组结果的更具体信息,则可能会制定出更好的方法。
Assuming that your active record class is called
MyActiveRecordClass
, the simplest approach should be sufficient:If you give more specific information about how you intend to display the grouped results it might be that a better approach can be worked out.