Yii 按类型获取记录

发布于 2024-12-14 11:31:06 字数 525 浏览 3 评论 0原文

我想知道 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 Tags. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小耗子 2024-12-21 11:31:06

使用 ActiveRecord 时,只需在 DBCriteria 中指定“索引”即可。因此,在查询中执行以下操作:

ActiveRecordClass::model()->findAll(array('index'=>'type_id'));

这将返回您之后的关联数组。 TBF 它可能执行完全相同的代码,但这显然比在任何地方执行它更容易使用。

When using ActiveRecord simply specify the "index" in the DBCriteria. So in a query do:

ActiveRecordClass::model()->findAll(array('index'=>'type_id'));

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.

花心好男孩 2024-12-21 11:31:06

假设您的活动记录类名为 MyActiveRecordClass,最简单的方法应该就足够了:

$models = MyActiveRecordClass::model()->findAll();
$groupedModels = array();

foreach ($models as $model) {
    $groupedModels[$model->typeID][] = $model;
}

如果您提供有关如何显示分组结果的更具体信息,则可能会制定出更好的方法。

Assuming that your active record class is called MyActiveRecordClass, the simplest approach should be sufficient:

$models = MyActiveRecordClass::model()->findAll();
$groupedModels = array();

foreach ($models as $model) {
    $groupedModels[$model->typeID][] = $model;
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文